Javascript 为什么使用超时显然会丢失此变量的引用?
为什么会这样:Javascript 为什么使用超时显然会丢失此变量的引用?,javascript,jquery,settimeout,Javascript,Jquery,Settimeout,为什么会这样: myelements.mouseenter(function() { clearTimeout(globaltimeoutvar); globaltimeoutvar = setTimeout(function() { var index = myelements.index(this); console.log(index); // -1 }, 150); }); 日志-1,而这: myelements.mouseenter(function()
myelements.mouseenter(function() {
clearTimeout(globaltimeoutvar);
globaltimeoutvar = setTimeout(function() {
var index = myelements.index(this);
console.log(index); // -1
}, 150);
});
日志-1,而这:
myelements.mouseenter(function() {
var index = myelements.index(this);
clearTimeout(globaltimeoutvar);
globaltimeoutvar = setTimeout(function() {
console.log(index); // 0, 1, 2, 3, what ever
}, 150);
});
记录正确的索引
或者:在超时回调中尝试访问引用/事件数据时,是否有任何引用/事件数据被破坏?尝试以下操作:您可以将$this存储在变量中,并在setTimeOut中使用它
正如@Regent所说,这是指为其调用函数的对象,因此这是指窗口
试试这个:您可以将$this存储在一个变量中,并在setTimeOut中使用它
正如@Regent所说,这是指为其调用函数的对象,因此这是指窗口
这取决于调用函数的方式
在全局上下文中,这是一个窗口
如果它作为对象方法调用,这就是对象
实际上,这两种情况都是对象方法情况,但在第一种情况下,对象是窗口
在第一个示例中,这是窗口,因为setTimeout实际上是window.setTimeout。在第二个示例中,这是您的对象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");
}
这取决于调用函数的方式
在全局上下文中,这是一个窗口
如果它作为对象方法调用,这就是对象
实际上,这两种情况都是对象方法情况,但在第一种情况下,对象是窗口
在第一个示例中,这是窗口,因为setTimeout实际上是window.setTimeout。在第二个示例中,这是您的对象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");
}
为了进一步解释@Bhushan和@abc123所说的话,正确确定范围的方法是确保上下文是正确的。尝试一下:
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);
});
为了进一步解释@Bhushan和@abc123所说的话,正确确定范围的方法是确保上下文是正确的。尝试一下:
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);
});
此内部函数指向调用该函数的对象。对于setTimeout,此对象是窗口。请看。@Regent是否发布答案?Alex,Bhushan Kawadkar已将此作为答案发布:因此您可以接受他的答案。但您是第一个:不寻找rep?此内部函数指向调用该函数的对象。对于setTimeout,此对象是窗口。请看。@Regent是否发布答案?Alex,Bhushan Kawadkar已将此作为答案发布:因此您可以接受他的答案。但您是第一个:不寻找代表?这确实有效,通常在为所用关键字存储此上下文时。这只是命名的常见约定,而不是规范。这确实有效,通常在为使用的关键字存储上下文时。不过,这只是命名的常见约定,而不是规范。