gpt4 book ai didi

Javascript 继承并丢失 'this' 的上下文

转载 作者:行者123 更新时间:2023-11-29 09:55:48 30 4
gpt4 key购买 nike

我在使用 John Resig 的简单 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 为您提供了一个绑定(bind)函数,以便您可以将上下文传递给该函数,但我在这里做类似的事情时运气不佳。有没有人有解决这个问题的起点?

谢谢!

最佳答案

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

你可以添加一个包装函数

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

或者您可以使用 bind 方法,如果它在您的浏览器中可用(或者您可以在 Prototype 中使用类似的功能)。

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

关于Javascript 继承并丢失 'this' 的上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11853727/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com