0

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

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

当我运行这段代码时,this参考是错误的......我错过了什么?

4

2 回答 2

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);
于 2013-07-01T14:16:53.253 回答
0

取决于方法。有关更多详细信息,请参阅我的其他 stackoverflow 答案
f() 是 o 的成员,但 of 是传递给 timeout 并通过函数的函数。这将为您提供所需的结果。

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

这是另一个使用函数调用调用的成员函数示例:参见我的小提琴

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

希望这可以帮助。

于 2013-07-04T05:09:31.953 回答