添加时返回为NaN的整数

Integer returning as NaN when added

本文关键字:整数 NaN 返回 添加      更新时间:2023-09-26

编写一些代码,当创建一个类的实例时,我的一个整数变量发生了一些奇怪的事情:

function Mat(x, y, spawner) {
    this.x = x;
    this.y = y;
    this.val = 1;
    this._spawner = spawner;
    this.newborn = true;
    this.bornTime = 0;
    this.spawnTimer = setInterval("this.bornTime++; console.log(this.bornTime);", 1000);
}

简洁明了的代码;在创建变量实例后的每一秒,它应该将bornTime变量增加1并记录它。

Mat.prototype.update = function() {
    if (this.bornTime >= 5) {
        this.bornTime = null;
        clearInterval(this.spawnTimer);
        this.newborn = false;
        console.log("Grown!");
    }
}

这个额外的代码会导致这个实例在5秒钟后"增长",但是当我检查控制台时,它显示bornTime不是一个数字(NaN)。

为什么会这样,有没有我看不到的解决方案?

setTimeout代码内部的this与外部不同(有关MDN的更多信息),因此您的代码实际上是在计算undefined++,即NaN

您必须创建另一个变量,并将函数传递给setTimeout,而不是让它评估字符串(顺便说一句,传递函数应该更快,看起来更好):

var that = this;
this.spawnTimer = setInterval(function(){
    that.bornTime++; 
    console.log(that.bornTime);
}, 1000);

我知道这是一个5年前的问题,但它是2018年的,这里有一个Es6语法解决方案,以避免绑定关键字this的额外步骤。

this.spawnTimer = setInterval(() => {
    this.bornTime++; 
    console.log(this.bornTime);
}, 1000);