[英]this keyword within a function of an object not returning expected value
我是编码和学习 this 关键字的新手,我期待 stephen object 中的 function 执行给它的计算(2022-1995)并显示该结果,但似乎 this 关键字不是定义,我不知道为什么在尝试修复它几个小时后。
const stephen = { firstName: 'Stephen', lastName: 'McColgan', job: 'Admin', friends: ['Chris', 'Simon', 'Thea', 'N/A'], hasDriversLicense: true, age: 1995, calcAge: function() { this.birthYear = 2022 - this.age; return this.birthYear; } }; console.log(stephen.age); console.log(stephen.birthYear);
您不是在显示age
之前调用calcAge()
function 。 所以它返回undefined
的原因this.birthYear
将在您调用 function 时被初始化。 所以首先你应该调用calcAge()
function 并显示age
。
在你的情况下, birthYear
和age
被交换了。 这是工作代码:
const stephen = { firstName: 'Stephen', lastName: 'McColgan', job: 'Admin', friends: ['Chris', 'Simon', 'Thea', 'N/A'], hasDriversLicense: true, birthYear: 1995, calcAge: function() { this.age = 2022 - this.birthYear; return this.age; } }; stephen.calcAge(); console.log(stephen.age);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.