javascript - 对javascript中的 'this'关键字感到困惑

标签 javascript jquery this

我已经很长时间没有使用 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

或(more compatible)

var _this = this;
setTimeout(function () {
    $(_this).data("Animating", false);
}, 550); 

关于javascript - 对javascript中的 'this'关键字感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12608807/

相关文章:

javascript - 相对时间 jQuery 插件(如 Twitter、FB 等)在 Safari 中中断?

javascript - 如果字符串的任何变体在 URL 中匹配,则返回 true

javascript - jQuery 鼠标悬停鼠标悬停问题

javascript - 提交后的wordpress联系表单7模态表单

javascript - react : How to redirect

javascript - 过滤 JSON 三重嵌套

jquery - 此输入元素接受一个文件名,该文件名只能以编程方式设置为空字符串

javascript - 在对象 `this` 中使用 "Unexpected token this"

java - 引用 JPanel Action 监听器内部的类

javascript - js单例 - 如何避免通过命名空间访问类成员