在setTimeout(javascript)中处理对象方法函数调用?

时间:2012-03-23 08:11:40

标签: javascript

代码:

​var a = function() {
   this.message = "hello";
    this.shout = function(){
        alert(this.message); // alerted undefined
    }
    this.Timer = setTimeout(this.shout, 3000);
}

var b = new a();

我在警告对话框中未定义。我在setTimeout中尝试了“this.shout()”,但是在查找shout时出现了DOM错误。我该如何处理?

3 个答案:

答案 0 :(得分:0)

this.message 

需要在this.shout函数内部,因为此时它已超出范围。

然后它会起作用:)

var a = function() {

    this.shout = function(){
        this.message = "hello";
        alert(this.message); // alerted undefined
    }
    this.Timer = setTimeout(this.shout, 3000);
}

var b = new a();

答案 1 :(得分:0)

函数this中的

shout指的是函数shout,而不是函数a

如果您在a范围内定义变量而不是使用此变量,您可以稍后参考它并获取它的值:

var a = function() {
    var message = "hello";
    this.shout = function(){
        alert(message); // Alerts hello
    }
    this.Timer = setTimeout(this.shout, 3000);
}

var b = new a();

或者,如果您愿意,可以存储引用,以便您可以使用self来引用a

var a = function() {
    this.message = "hello";
    var self = this;

    this.shout = function(){
        alert(self.message); // Alerts hello
    }
    this.Timer = setTimeout(this.shout, 3000);
}

var b = new a();

答案 2 :(得分:0)

“set”中的“this”是你之前必须在外部“this”中获取的settimeout实例

var a = function()
{
   this.message = "hello";
   this.shout = function()
   {
        alert(this.message); // alerted undefined
   }
   var t = this;
   this.Timer = window.setTimeout(function()
  {
    t.shout();
  }, 3000);
}

var b = new a();