我甚至不确定如何提出这个问题,但我已经将代码减少到最简单的可能示例:
function Handler() {}
Handler.prototype.texts = [];
Handler.prototype.add = function(d) {
this.texts.push(d);
};
Handler.prototype.tick = function() {
console.log( this.texts );
};
var x = new Handler();
setInterval( x.tick, 5000 );
x.add('beatles');
Run Code Online (Sandbox Code Playgroud)
当setInterval调用x.tick时,它为this.texts提供一个undefined值 - 当然,也就是this.虽然我可以解决问题
setInterval( x.tick, 5000, x );
// and ... in the prototype
Handler.prototype.tick = function(myObj) {
console.log( myObj.texts );
}
Run Code Online (Sandbox Code Playgroud)
感觉有点笨重.有一个更好的方法吗?
x像这样做一个upvalue
setInterval(function(){
x.tick()
}, 5000);
Run Code Online (Sandbox Code Playgroud)
当setInterval火灾,封闭将周围的实例创建x.