简体   繁体   English

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

[英]Handling object method function calls in setTimeout (javascript)?

Code: 码:

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

var b = new a();

I get undefined in the alert dialog. 我在警报对话框中未定义。 I've tried "this.shout()" in setTimeout but then there is a DOM error on finding shout. 我已经在setTimeout中尝试过“ this.shout()”,但是找到喊叫时出现了DOM错误。 How do I deal with this? 我该如何处理?

this.message 

needs to be inside the this.shout function, since at the moment it's out of scope. 需要在this.shout函数内部,因为此刻它不在范围内。

Then it will work :) 然后它将起作用:)

var a = function() {

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

var b = new a();

this in your function shout refers to the function shout , rather than the function a this在你的函数shout指功能shout ,而不是功能的a

If you define your variable in the scope of a instead of using this, you can refer to it later on and get it's value: 如果你的范围定义的变量a ,而不是使用这个的,你可以参考它以后,得到它的价值:

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

var b = new a();

Or if you'd like you can store a reference instead, so that you can use self to refer to a : 或者,如果你愿意,你可以存储一个参考,而不是,这样就可以使用自指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();

"this"inside settimeout is the settimeout instance you must get previously in a var the outside "this" “ this”内部settimeout是必须在外部“ this”外部的var中预先获取的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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM