gpt4 book ai didi

javascript - 添加时返回 NaN 的整数

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:49:26 27 4
gpt4 key购买 nike

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

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);

关于javascript - 添加时返回 NaN 的整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18283095/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com