Javascript 在setInterval中调用方法时出错
我在setInterval中调用方法时遇到问题。。。这是我的一段代码Javascript 在setInterval中调用方法时出错,javascript,setinterval,undefined-function,Javascript,Setinterval,Undefined Function,我在setInterval中调用方法时遇到问题。。。这是我的一段代码 var example = function(){ this.animate = function(){ console.log("Animate."); } this.updateTimer = function(){ // This is being called... this.timer = setInterval(function(){
var example = function(){
this.animate = function(){
console.log("Animate.");
}
this.updateTimer = function(){ // This is being called...
this.timer = setInterval(function(){
this.animate(); // A "Undefined Is Not A Function" error is being thrown here.
}, 1);
}
}
使用BIND(如@torazaburo所说)
也许是最佳实践
或使用闭包
您不能在setInterval中使用此
使用此代码
var example = function(){
this.animate = function(){
console.log("Animate.");
}
this.updateTimer = function(){ // This is being called...
this.timer = setInterval(function(){
example.animate(); // A "Undefined Is Not A Function" error is being thrown here.
}, 1);
}
}
编辑this.animate()
到example.animate()
使用此代码
var example = function(){
this.animate = function(){
console.log("Animate.");
}
this.updateTimer = function(){ // This is being called...
this.timer = setInterval(function(){
example.animate(); // A "Undefined Is Not A Function" error is being thrown here.
}, 1);
}
}
或者,如果您愿意,setInterval(this.animate.bind(this),1)
。这个问题已经被问了大概半打次了。您需要仔细阅读此
的确切含义及其来源。你试过调试这个吗?只要在有问题的行上放置一个断点并检查this
的值,就可以为您提供所需的所有线索。另请参阅Mike West的。迈克是个很好的作家,这篇文章写得很好。
var example = function(){
this.animate = function(){
console.log("Animate.");
}
this.updateTimer = function(){ // This is being called...
this.timer = setInterval(function(){
example.animate(); // A "Undefined Is Not A Function" error is being thrown here.
}, 1);
}
}