2017-06-06 71 views
2

无法使用我有这个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

回答

3

当你传递一个匿名函数时,它会得到它自己的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.

+1

那么你应该使用'内回调self' – yurzui

+0

@yurzui是正确的。用'self'替换JQuery中的'this'。 – Ethilium

+2

对不起,你们都需要更多的咖啡。示例已更新。 –