JS - 使用timeOut时的这个引用

时间:2013-07-01 14:14:40

标签: javascript web timeout this

使用timeOut时如何保留此引用?

var o = {
   f:function(){
     console.log(this)
     setTimeout(this.f,100);
     }
}
o.f();

当我运行此代码时,this引用是错误的...我错过了什么?

2 个答案:

答案 0 :(得分:0)

您可以将参数传递给setTimeout,作为第三个参数。这样你就可以传递参考。

但是,如果你试图用new创建一些“面向对象”的东西,你应该使用一个函数来代替:

function obj() {
  this.publicFunction = function() {
    console.log("I'm public!");
  };
  var privateFunction = function() {
    console.log("Only accessible from inside this instance!");
  }
}

var objInstance = new obj();
objInstance.publicFunction(); // Logs w/o problem
objInstance.privateFuntion() // Undefined!

编辑(再次): 但是如果你真的热衷于出于某种原因使用对象,this在一个对象中,实际上引用了对象本身。但由于对象被定义为变量(在您的情况下也是全局变量),因此可以直接引用该名称而不是this。这里:

var o = {
  f: function() {
    console.log(this);  // Will log the object 'o'
    console.log(o);  // Same as above
  }
};

setTimeout(o.f, 100);

答案 1 :(得分:0)

取决于方法。有关详细信息,请参阅我的other stackoverflow answer  f()是o的成员,但是o.f是传递给超时的函数,并使用函数调用。 这将为您提供所需的结果。

var o = {
   f:function(){
     console.log(o)
     setTimeout(o.f,100);
     }
}
o.f();

以下是使用函数调用调用的成员函数的另一个示例:请参阅我的Fiddle

var anObject = {
    test: function(isThis, message) {
        if(this === isThis) 
            console.log("this is " + message);
        else
            console.log("this is NOT " + message);
    }//I am a method
};

//method invocation
anObject.test(anObject, "anObject"); //this is anObject

var aFunction = anObject.test;
//functional invocation
aFunction(anObject, "anObject with aFunction"); //this is NOT anObject with aFunction
aFunction(this, "global with aFunction");//this is global with aFunction

希望这有帮助。