我的JavaScript代码是如何得到未定义的结果的



我在JS中练习创建一个对象,并创建了以下对象:

const jonas = {
firstName: 'Jonas',
lastName: 'Schmedtmann',
birthYear: 1991,
job: 'teacher',
friends: ['Michael', 'Peter', 'Steven'],
hasDriversLicense: false,
calcAge: function () {
this.age = 2037 - this.birthYear;
return this.age;
},
};

当我想用以下代码打印函数calcAge的输出时,会发生一件奇怪的事情:

console.log(jonas.age);

浏览器输出";未定义的";用于CCD_ 2命令。

有人能告诉我哪里搞错了吗?

谢谢!

const jonas = {
firstName: 'Jonas',
lastName: 'Schmedtmann',
birthYear: 1991,
job: 'teacher',
friends: ['Michael', 'Peter', 'Steven'],
hasDriversLicense: false,
calcAge: function () {
this.age = 2037 - this.birthYear;
return this.age;
},
};

这里的calcAge是一个函数声明,它将通过访问同一对象的birthYear属性来向该对象添加age属性。一切听起来都很好,但只有当函数为called/executed时,这一切才会发生。

CCD_ 6和CCD_。因此控制台输出为undefined,因为该函数从未被称为

所以需要调用函数

jonas.calcAge()

console.log(jonas.calcAge());将为您提供年龄的值

jonas.age = jonas.calcAge();

然后

console.log(jonas.age);

相关内容

最新更新