问题描述
我正在尝试使用以下代码将出生年份作为结果,但结果是 NaN。
function person(name,age){
this.name = name;
this.age = age;
this.yearOfBirth = bornYear;
}
function bornYear(){
return 2020 - this.age;
}
document.write(bornYear());
我在这里缺少什么?
解决方法
试试这个:
function bornYear(){
return 2020 - parseInt(this.age);
}
,
您没有创建 person
的实例,也没有调用该实例的属性:
-
bornYear
引用this
,这似乎是一个person
实例,因此您必须以某种方式将this
绑定到它。 - 当您定义属性
yearOfBirth
时,调用那个方法是合适的。
此外,您的 bornYear
函数仅限于 2020 年。您应该使用 Date
构造函数获取当前年。
这是它的工作原理:
function person(name,age){
this.name = name;
this.age = age;
this.yearOfBirth = bornYear.bind(this); // bind this
}
function bornYear(){
// Use the current year to calculate year of birth
return new Date().getFullYear() - this.age;
}
// First create an instance,then call the method
document.write(new person("Helen",18).yearOfBirth());
不过,在原型上定义这样的方法更为常见,并且构造函数名称以大写字母 (Person
) 开头。
此外,在这种情况下使用 document.write
是不好的做法。使用 console.log
。
标准的方式是这样的:
class Person {
constructor(name,age) {
this.name = name;
this.age = age;
}
bornYear() {
return new Date().getFullYear() - this.age;
}
}
console.log(new Person("Helen",18).bornYear());
您似乎将面向对象编程与函数式编程风格混为一谈。如果您想像现在一样使用 this
,您必须执行以下操作:
function Person(name,age) {
this.name = name;
this.age = age;
this.yearOfBirth = () => {
return new Date().getFullYear() - this.age;
};
}
let newPerson = new Person('Foo',25);
document.write(newPerson.yearOfBirth());