【问题标题】:Method error: Method name not defined [duplicate]方法错误:方法名称未定义[重复]
【发布时间】:2016-04-30 04:26:26
【问题描述】:

为什么这段代码不起作用?我正在尝试使用该方法来添加属性,然后将添加的属性分配给它自己的值。

function howLongILivedSomewhere(college, home1, home2) {
    this.birthHome = 18;
    this.college = college;
    this.home1 = home1;
    this.home2 = home2;

    this.calcYearsAlive = function() {
    return birthHome + college + home1 +home2;
    };

    this.yearsAlive = calcYearsAlive();
}

var me = new howLongILivedSomewhere(4, 2, 3);

console.log(me);

【问题讨论】:

  • 在方法或方法调用中也使用这个关键字
  • @Venkatraman 谢谢!
  • 查看我的答案,为您提供解决方案!

标签: javascript object methods


【解决方案1】:

将构造函数更新为:

function howLongILivedSomewhere(college, home1, home2) {
    this.birthHome = 18;
    this.college = college;
    this.home1 = home1;
    this.home2 = home2;

    this.calcYearsAlive = function() {
      return this.birthHome + this.college + this.home1 + this.home2;
    };

    this.yearsAlive = this.calcYearsAlive();
}

var me = new howLongILivedSomewhere(4, 2, 3);

console.log(me);

当您需要访问对象属性时使用this 关键字(see here 更多详细信息)。

【讨论】:

  • 其实还是不行。它给了我错误消息: calcYearsAlive 未定义。
  • 你是对的。答案已更新。
  • 太棒了!这次奏效了。感谢您的帮助!
【解决方案2】:

您在方法/属性调用期间错过了this 关键字。尝试如下。

  function howLongILivedSomewhere(college, home1, home2) {
    this.birthHome = 18;
    this.college = college;
    this.home1 = home1;
    this.home2 = home2;

    this.calcYearsAlive = function() {
      return this.birthHome + this.college + this.home1 + this.home2;
    };

    this.yearsAlive = this.calcYearsAlive();
}

var me = new howLongILivedSomewhere(4, 2, 3);

console.log(me.yearsAlive); // output: 27

什么是this关键字?

与其他语言相比,函数的 this 关键字在 JavaScript 中的行为略有不同。严格模式和非严格模式也有一些区别。

参考:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this
How does "this" keyword work within a function?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-19
    • 1970-01-01
    • 2017-09-24
    • 2011-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多