javascript - 方法错误 : Method name not defined

标签 javascript object methods

<分区>

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

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);

最佳答案

您在方法/属性调用期间错过了 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?

关于javascript - 方法错误 : Method name not defined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34965878/

相关文章:

javascript - 在下划线模板中使用整数变量作为键

c# - 如何将数组对象列出来

java - 单击按钮时不执行方法 [JavaFX]

javascript - 反转数组,循环中的 pop 方法未弹出完成

javascript - 为什么 jQuery 文件 uploader 中的 processQueue 在这里不起作用?

javascript - Vue组件中继承CSS

javascript - 使用 es6 数组函数迭代对象键以用所需键替换所选键

c# - Unity3D,C#如何保存对象的位置并稍后重新启动它们?

object - !对象方法后 typescript 中的运算符

powershell - 如何使用属性和方法创建[PsCustomObject]