gpt4 book ai didi

javascript - 为什么使用超时显然会丢失 this 变量的引用?

转载 作者:行者123 更新时间:2023-11-28 15:35:01 25 4
gpt4 key购买 nike

为什么会这样:

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指的是调用函数的对象,因此this指的是window

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

关于javascript - 为什么使用超时显然会丢失 this 变量的引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25931476/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com