繁体   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