簡體   English   中英

mobx 的 `action.bound` 和 class 函數上的箭頭函數之間的區別?

[英]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產生影響:

  1. 綁定 :如何this在產生的功能綁定。
  2. 原型 :如果生成的函數在原型中。

總而言之,這些是規則:

  • @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 = () => {}
}

這就是storeInstance的樣子: 在此輸入圖像描述

正如您所指出的, arrow = () => {}不是原型的一部分。 要回答你的問題, @action arrow = () => {}將不會產生原型中的函數。 看起來@action保留了以前的行為。 但是, @action.bound將始終生成原型中的函數。

現在它在手冊中也有很好的描述)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM