gpt4 book ai didi

JavaScript : setTimeout use on an anonymous function expression

转载 作者:行者123 更新时间:2023-11-28 18:29:16 25 4
gpt4 key购买 nike

我最近开始学习 javascript 来帮助维护一些东西,今天遇到了这个问题:

this.moveChar = function(){  
// body here
setTimeout(moveChar,1000);
}

this.initialise= function(){
this.moveChar();
}

当调用initialise时,我期望调用moveChar,然后每1000ms重复调用一次

然而,实际发生的情况是 moveChar 被调用一次,就这样了。根据我读到的其他 stackoverflow 帖子,我怀疑这可能与表达而不是声明的函数有关。我尝试过使用

this.moveChar = function recMove(){  
// body here
setTimeout(recMove,1000);
}

也没有运气。

关于如何解决这个问题有什么建议吗?

编辑:我需要做的主要事情是每秒调用一次 moveChar 函数。如果有比 setTimeout 递归更好的方法,我愿意接受

最佳答案

this.moveCharmoveChar 不同,除非 this 是像 window 这样的全局范围对象。

this.moveChar 是对象的属性,而 moveChar 将引用可见作用域链中的任何变量。

您可以将其更改为一些内容,以保持正在使用的任何对象的范围:

使用 arrow function

this.moveChar = function(){  
// body here
setTimeout(()=>this.moveChar(),1000);
}

使用.bind()

this.moveChar = function(){  
// body here
setTimeout(this.moveChar.bind(this),1000);
}

关于JavaScript : setTimeout use on an anonymous function expression,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38451759/

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