我正在创建一个程序来使用 javascript 重复移动对象。函数在分开时可以工作,但是当我尝试使用 OOP 模式时,它会反复出现一个奇怪的错误,说
Uncaught TypeError: this.Move is not a function
这是我的代码
function Bot(){
this.XPos =0;
this.YPos=0;
this.AsyncMove=setInterval(function(){
this.XPos+=10;
this.YPos+=10;
this.Move();
},100);
}
Bot.prototype = {
constructor:Bot,
Move:function(){
console.log(this.XPos+" ,"+this.YPos);
}
};
最佳答案
你应该像这样将当前实例绑定(bind)到匿名函数
this.AsyncMove=setInterval(function(){
this.XPos+=10;
this.YPos+=10;
this.Move();
}.bind(this),100);
关于OOP 样式的 Javascript setInterval() 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30117534/