JAVASCRIPT:在 document.write() 中调用函数后获取 NaN 结果

问题描述

我正在尝试使用以下代码将出生年份作为结果,但结果是 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());

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...