为什么这段代码不起作用?我正在尝试使用该方法来添加属性,然后将添加的属性分配给它自己的值。
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);
答案 0 :(得分:1)
您在方法/媒体资源调用期间错过了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
关键字?与其他语言相比,函数的此关键字在JavaScript中的行为略有不同。它在严格模式和非严格模式之间也有一些区别。
<强>参考:强>
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this
How does "this" keyword work within a function?
答案 1 :(得分:0)
将构造函数更新为:
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更多详细信息)。