javascript - 这在完整功能中不可用

标签 javascript jquery angular typescript

我有这个 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在我的完整功能中?

最佳答案

当您传入匿名函数时,它会获得自己的 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 上的文档:

An arrow function expression has a shorter syntax than a function expression and does not bind its own this, arguments, super, or new.target. These function expressions are best suited for non-method functions, and they cannot be used as constructors.

如果您能够在项目中使用箭头函数,它将如下所示:

$("#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.

关于javascript - 这在完整功能中不可用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44393826/

相关文章:

javascript - 选择单选按钮后的文本输入字段

javascript - 是否可以在不使用html5的情况下在IE8和其他主流浏览器中实现模糊效果和运动模糊效果?

javascript - OnClick 函数无法正常工作以重新定位内容

单击音频播放的 Javascript 延迟

html - 在 Angular8 的 Assets 文件夹中为 Logo 获取不同的构建

angular - 禁用 ngbDatepicker 输入

javascript - 在 D3 中移动固定节点

javascript - 出现未知语法错误

html - 使用组件函数设置 HTML 对象的样式

javascript - StartsWith() 不能与 takeWhile() 一起使用