gpt4 book ai didi

JavaScript 无法在另一个函数中调用原型(prototype)函数

转载 作者:行者123 更新时间:2023-11-27 23:29:24 24 4
gpt4 key购买 nike

我一直在寻找答案,但我发现的一切似乎都表明我没有做错任何事。我试图在另一个函数中调用原型(prototype)函数,但我不断收到它不是函数的错误。

由于某种原因,它只发生在一个特定的方法(勾选)内,其余的方法使用相同的方法没有问题。

这是我的代码:

Timer.prototype.getTimeRemaining = function(){
return this.startTime - this.currentTimeTimed;
}

Timer.prototype.updateElement = function(){
document.getElementById("clock").innerHTML = this.getTimeRemaining();
return true;
}

Timer.prototype.tick = function(){
if (this.running){
this.currentTimeTimed += timePassedInMilliseconds;
}
this.getTimeRemaining();
this.updateElement();
}

所以我得到的错误是在tick()中:Uncaught TypeError: this.getTimeRemaining() is not a function。

在进行更多测试时,我想我找到了原因:我认为这是因为刻度函数是从一个间隔调用的。我不确定,但这是我能想到的唯一与其他功能不同的地方。但我不知道如果是由间隔引起的,我应该如何更改我的代码。

提前致谢。

最佳答案

我发现我需要在 setInterval 中使用 .bind(this)。

关于JavaScript 无法在另一个函数中调用原型(prototype)函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34700866/

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