2017-06-06 73 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

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