为什么这样:
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);
});
记录正确的索引?
或者:尝试在超时回调中访问它时,是否有任何参考/事件数据被破坏?
答案 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
取决于函数的调用方式。
在全球范围内,this
为window
。
如果以对象方式调用它this
是对象。
(实际上两者都是对象方法的情况,但在第一种情况下,对象是window
)
在您的第一个示例中,this
为window
,因为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);
});