【问题标题】:JS - this reference when using timeOutJS - 使用 timeOut 时的此参考
【发布时间】:2013-07-04 13:09:31
【问题描述】:

当我使用 timeOut 时如何保留 this 引用?

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

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

【问题讨论】:

  • 该代码在语法上不正确。
  • o 是一个对象文字,因此您的代码通常是错误的(t​​his.f = 甚至 f = 都不起作用!)
  • 应该是什么?一个函数?对象文字?你想怎么用你的代码???

标签: javascript web timeout this


【解决方案1】:

依赖于 方法。更多详情请看我的other stackoverflow answer
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

希望这会有所帮助。

【讨论】:

    【解决方案2】:

    您可以将参数作为第三个参数传递给 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);
    

    【讨论】:

    • 是的,我只记得.. 但是,我认为 OP 适合“面向对象”的东西,我对其进行了编辑并添加了一个示例。
    • 我认为将附加参数传递给 setTimeout 存在兼容性问题,但我不知道细节。替代解决方案是使用闭包或 Function.prototype.bind
    猜你喜欢
    • 2015-07-14
    • 1970-01-01
    • 2017-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多