我试图在方法内使用setTimeout()作为递归函数。我假设我正在使用'这个'范围错误但是。这是一个例子。
(function(scope){
function gamePlay(){
// this.initialize();
}
gamePlay.prototype.droidMovement = function(){
console.log('droid is moving');
this.droidShoot();
}
gamePlay.prototype.droidShoot = function(){
console.log('droidShoot() has been fired');
setTimeout(this.droidShoot,1000);
}
scope.gamePlay = gamePlay;
})(window);
var game = new gamePlay();
game.droidMovement();
我尝试过setTimeout 3种方法。
//this way repeats the function 2 times then stops
setTimeout(this.droidShoot,1000);
//this gives me an error
setTimeout(function(){this.droidShoot()},1000);
//this fires the function in a loop but doesnt wait the second
setTimeout(this.droidShoot(),1000);
任何人都可以解释一下我做错了什么吗?非常感谢提前。
答案 0 :(得分:-1)
您可能希望从setTimeout
的定义中删除droidShoot
,并将setTimeout(this.droidShoot, 1000)
替换为setInterval(this.droidShoot, 1000
。
setInterval将以1s间隔重复自动调用this.droidShoot