我无法在setInterval中调用方法...以下是我的代码片段...
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);
}
}
答案 0 :(得分:1)
也许是最佳实践
http://jsfiddle.net/rnrlabs/Lnmex1y7/
var example = function(){
this.animate = function(){
console.log("Animate.");
}
this.updateTimer = function() { // This is being called...
this.timer = setInterval(this.animate.bind(this), 1);
}
}
http://jsfiddle.net/rnrlabs/zk6hdnf2/
var example = function(){
var self = this; // this creates a closure
this.animate = function(){
console.log("Animate.");
}
this.updateTimer = function(){
this.timer = setInterval(function(){
// 'this' here means window element.
self.animate();
}, 1);
}
}
答案 1 :(得分:0)
你不能在setInterval中使用this
使用此代码
edite 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);
}
}