我有这个 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/