【问题标题】:This not available in complete function [duplicate]这在完整功能中不可用[重复]
【发布时间】:2017-11-07 16:42:00
【问题描述】:

我有这个 jQuery 函数

$("#edit-modal").animate({ width: "90%" }, 400, function () {
    this.registrationsPanelWidth = $("#edit-modal").width() - this.modalWidth - 20;
    console.log(this.modalWidth);
});

但是在function() 中似乎this. 不知道或不可用,这意味着console.log(this.modalWidth); 导致未定义。

如何在我的完整函数中使用我的this.property

【问题讨论】:

    标签: javascript jquery angular typescript


    【解决方案1】:

    当你传入一个匿名函数时,它会获得自己的this 变量。

    解决此问题的最快方法是在外部范围内创建对this 的闭包引用,并在回调中使用引用变量。

    var self = this;
    $("#edit-modal").animate({ width: "90%" }, 400, function () {
        self.registrationsPanelWidth = $("#edit-modal").width() - self.modalWidth - 20;
        console.log(self.modalWidth);
    });
    

    顺便说一下,这是 ES6 箭头函数的完美用例。来自 MDN 上的文档:

    箭头函数表达式的语法比函数表达式短,并且不绑定自己的 this、arguments、super 或 new.target。这些函数表达式最适合非方法函数,它们不能用作构造函数。

    如果你能够在你的项目中使用箭头函数,它应该是这样的:

    $("#edit-modal").animate({ width: "90%" }, 400, () => {
        this.registrationsPanelWidth = $("#edit-modal").width() - this.modalWidth - 20;
        console.log(this.modalWidth);
    });
    

    See the documentation on MDN for more information on arrow functions.

    【讨论】:

    • 那么你应该在回调中使用self
    • @yurzui 是对的。将 JQuery 中的 this 替换为 self
    • 对不起,你们都需要更多的咖啡。示例已更新。
    猜你喜欢
    • 2017-02-20
    • 2016-03-15
    • 1970-01-01
    • 1970-01-01
    • 2014-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多