繁体   English   中英

object 的 function 中的这个关键字不返回预期值

[英]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


在你的情况下, birthYearage被交换了。 这是工作代码:

 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM