[英]Difference between mobx's `action.bound` and arrow functions on class functions?
在帶有 babel 的 class 上使用箭頭函數將其轉譯,因此定義綁定在構造函數中。 因此它不在原型中,並且在繼承時不能通過super
獲得。 通過創建許多實例進行擴展時,它的效率也不高。
關於這個主題的博客文章比較多,但我只是想知道在使用 babel 時,與箭頭函數相比,mobx.action.bound 的處理方式有何不同。
比較兩者:
class Example {
test = () => {
console.log(this.message)
}
}
class Example {
@action.bound
test() {
console.log(this.message)
}
}
@action
和@action.bound
有2個變量對@action
@action.bound
產生影響:
this
在產生的功能綁定。 總而言之,這些是規則:
@action
保留原始函數的綁定和原型包含。 如果原始函數未綁定,則結果不會,反之亦然。 如果原始函數不在原型中,結果將不會,反之亦然。 @action.bound
將始終生成一個綁定的函數,該函數位於原型中。 您可以像這樣輕松測試:
class Store {
unbound() {
console.log('unbound', this)
}
arrow = () => {
console.log('arrow', this)
}
}
const storeInstance = new Store()
const unbound = storeInstance.unbound
const arrow = storeInstance.arrow
unbound()
arrow()
// console displays:
// unbound undefined
// arrow Store
現在讓我們嘗試添加@action
:
class Store {
@action
unbound() {
console.log('unbound', this)
}
@action
arrow = () => {
console.log('arrow', this)
}
}
const storeInstance = new Store()
const unbound = storeInstance.unbound
const arrow = storeInstance.arrow
unbound()
arrow()
// console still displays:
// unbound undefined
// arrow Store
現在讓我們嘗試添加@action.bound
:
class Store {
@action.bound
unbound() {
console.log('unbound', this)
}
@action.bound
arrow = () => {
console.log('arrow', this)
}
}
const storeInstance = new Store()
const unbound = storeInstance.unbound
const arrow = storeInstance.arrow
unbound()
arrow()
// console now displays:
// unbound Store
// arrow Store
如您所見, @action
維護函數的綁定(或缺少綁定)。 同時, @action.bound
將始終返回綁定函數,從而將未綁定函數轉換為綁定函數,並且已綁定函數將保持有界。
至於您對繼承的關注,這里是Store
定義:
class Store {
unbound() {}
arrow = () => {}
@action unboundAction() {}
@action.bound unboundActionBound() {}
@action arrowAction = () => {}
@action.bound arrowActionBound = () => {}
}
正如您所指出的, arrow = () => {}
不是原型的一部分。 要回答你的問題, @action arrow = () => {}
將不會產生原型中的函數。 看起來@action
保留了以前的行為。 但是, @action.bound
將始終生成原型中的函數。
現在它在手冊中也有很好的描述)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.