为什么使用超时显然会丢失对此变量的引用?

时间:2014-09-19 10:11:12

标签: javascript jquery settimeout

为什么这样:

myelements.mouseenter(function() {  
  clearTimeout(globaltimeoutvar);
  globaltimeoutvar = setTimeout(function() {
  var index = myelements.index(this);
    console.log(index); // -1
  }, 150);
});

log -1,同时:

myelements.mouseenter(function() {
  var index = myelements.index(this);
  clearTimeout(globaltimeoutvar);
  globaltimeoutvar = setTimeout(function() {
    console.log(index); // 0, 1, 2, 3, what ever
  }, 150);
});

记录正确的索引?

或者:尝试在超时回调中访问它时,是否有任何参考/事件数据被破坏?

3 个答案:

答案 0 :(得分:2)

试试这个:您可以将$(this)存储在变量中并在setTimeOut

中使用它

正如@Regent所说,this指的是调用函数的对象,因此this引用window

myelements.mouseenter(function() {  
  var myelementsThis = $(this);
  clearTimeout(globaltimeoutvar);
  globaltimeoutvar = setTimeout(function() {
  var index = myelements.index(myelementsThis);
    console.log(index); // -1
  }, 150);
});

答案 1 :(得分:1)

this取决于函数的调用方式。

  1. 在全球范围内,thiswindow

  2. 如果以对象方式调用它this是对象。

  3. (实际上两者都是对象方法的情况,但在第一种情况下,对象是window

    在您的第一个示例中,thiswindow,因为setTimeout()实际上是window.setTimeout()。在您的第二个示例中this是您的对象myelements

    请参阅以下示例:

    var globalFunc = function(){ return this
    };
    
    if(globalFunc() === window){
      alert("this is window");
    }
    
    var someObject = {};
    someObject.method = function(){ return this };
    if(someObject.method() === someObject){
      alert("this is the object");
    }

答案 2 :(得分:1)

为了进一步解释@Bhushan和@ abc123所说的内容,正确确定this范围的方法是确保上下文正确。试一试:

myelements.mouseenter(function() {  

  var that = this; // Store the correct context in a variable.

  clearTimeout(globaltimeoutvar);
  globaltimeoutvar = setTimeout(function() {

  var index = myelements.index(that); // Scoped correctly to the myelements object.
  var wrongIndex = myelements.index(this); // Scoped to the window object via setTimeout.

    console.log(index); // Correct value.
  }, 150);
});