我已经很长时间没有使用 Javascript 了,今天一直在用它来提神。 this
关键字总是让我着迷。我知道在 jQuery 事件处理程序中,例如单击事件,this
指的是触发事件的元素。即使我的函数没有参数,this
是如何传递给我作为回调给它的函数的?
给定以下代码:
$("tr.SummaryTbRow").data("Animating", false);
$("tr.SummaryTbAltRow").data("Animating", false);
$("tr.SummaryTbRow").click(function () {
if ($(this).data("Animating") == false) {
if ($(this).next(".Graph").css("display") == "none") {
$(this).data("Animating", true);
//Part I am questioning.
setTimeout(function () {
$(this).data("Animating", false);
}(this), 550);
$(this).next(".Graph").slideRow('down', 500);
}
else {
$(this).data("Animating", true);
$(this).next(".Graph").slideRow('up', 500);
}
}
});
我正在尝试弄清楚如何将类为 SummaryTbRow
的元素表行传递给我的 setTimeout 回调函数。 jQuery 是否以与我对匿名回调函数所做的类似的方式传递 this
?函数中的 this
是否引用了我传入的 this
?
我知道我可以这样做:
setTimeout(function (element) {
$(element).data("Animating", false);
}(this), 550);
但我想弄清楚 jQuery 如何能够将 this
传递给我的回调函数,即使我的函数采用 0 个参数。
最佳答案
为了回答您最后一个问题,您可以将您选择的接收器传递给 javascript 中的一个函数,例如使用 call :
someFunction.call(someObject);
在 someFunction
中,this
将是 someObject
。
在你的情况下,你似乎想要的是
setTimeout(function (element) {
$(element).data("Animating", false);
}, 550, this); // this will be passed as element to the callback
var _this = this;
setTimeout(function () {
$(_this).data("Animating", false);
}, 550);
关于javascript - 对javascript中的 'this'关键字感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12608807/