JS-使用timeOut时的此引用

JS - this reference when using timeOut

本文关键字:引用 使用 timeOut JS-      更新时间:2023-09-26

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

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

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

这取决于调用方法。有关更多详细信息,请参阅我的另一个stackoverflow答案
f()是o的一个成员,但o.f是传递给timeout并通过函数调用调用的函数。这将给你带来想要的结果。

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

希望这能有所帮助。

您可以将参数作为第三个参数传递到setTimeout中。这样你就可以传递一个引用。

然而,如果你试图用新的东西创建一些"面向对象"的东西,你应该使用一个函数来代替:

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);