2012-08-07 59 views
3

我正在使用John Resig的Simple JavaScript Inheritance,并遇到一个问题,我失去了'this'引用的内容。使用此代码:Javascript继承和丢失'this'的上下文

var Runner = Class.extend({ 
init: function() { 
    this.update(); 
    if(!this.interval) { 
    this.interval = setInterval(this.update, this.period * 1000); 
    } 
}, 
stop: function() { 
    clearInterval(this.interval); 
}, 
update: function() { 
    this.success() 
}, 
success: function(){ 
} 
}); 

var SubRunner = Runner.extend({ 
update: function() { 
    this._super(); 
}, 
success: function(){ 
    alert('sub runner success'); 
} 
}); 

运行p = new SubRunner()作品我希望和警报sub runner success第一次。第一次运行后,尝试在错误的“this”(窗口)上运行成功函数。

我知道Prototype为您提供了一个绑定函数,以便您可以将上下文传递给该函数,但我在此处做类似的事情时没有任何运气。有没有人有一个起点来弄清楚这一点?

谢谢!

+0

它看起来像我忽略了setTimeout,并且过于强烈地关注成功函数。感谢或帮助大家! – 2012-08-07 21:06:40

回答

3

问题是当您将this.update传递给setInterval函数时。在Javascript中,“this”取决于你是否使用点符号调用函数,并且如果将函数作为回调函数传递或将它们存储在变量中,函数将不会记住它们来自哪里。

您可以添加一个包装函数

var that = this; 
setTimeout(function(){ that.update() }, this.perios*1000) 

,或者您可以使用,如果其提供的绑定方法在你的浏览器(或者你可以在原型使用类似的功能)。

setTimeout(this.update.bind(this), this.period*1000) 
1

当您将this.update传递给setInterval时,将失去上下文。 最简单的办法是做

var that = this; 
this.interval = setInterval(function() { that.update() }, this.period * 1000); 
1
this.interval = setInterval(this.update, this.period * 1000); 

setTimeout调用它调用它在全球范围内(它设置thiswindow)的功能。

您需要传递一个函数,调用this.update

var self = this; 
this.interval = setInterval(function(){ 
    self.update(); 
}, this.period * 1000);