Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/apache-flex/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript继承和丢失';这';_Javascript_Class_Inheritance_This - Fatal编程技术网

Javascript继承和丢失';这';

Javascript继承和丢失';这';,javascript,class,inheritance,this,Javascript,Class,Inheritance,This,我使用的是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() { clea

我使用的是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()
的工作与我预期的一样,并在第一次提醒
SubRunner success
。在第一次运行之后,它会尝试在错误的“this”(窗口)上运行success函数

我知道Prototype为您提供了一个绑定函数,这样您就可以将上下文传递给该函数,但我在这里没有做过类似的事情。有人有一个起点来解决这个问题吗


谢谢

问题在于将此.update传递给setInterval函数时。在Javascript中,“this”取决于是否使用点表示法调用函数,如果将函数作为回调传递或存储在变量中,函数将不会记住它们来自何处

您可以添加一个包装器函数

var that = this;
setTimeout(function(){ that.update() }, this.perios*1000)
或者,如果bind方法在浏览器中可用,则可以使用它(或者可以在Prototype中使用类似的函数)


将this.update传递给setInterval时,将丢失上下文。 最简单的解决办法是

var that = this;
this.interval = setInterval(function() { that.update() }, this.period * 1000);
setTimeout
调用一个函数时,它会在全局范围内调用该函数(它将
设置为
窗口

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

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

看起来我忽略了setTimeout,过于专注于success函数。谢谢大家的帮助!
this.interval = setInterval(this.update, this.period * 1000);
var self = this;
this.interval = setInterval(function(){
    self.update();
}, this.period * 1000);