ES6:从类/函数中构造方法?

时间:2016-01-05 23:46:46

标签: javascript ecmascript-6

我想知道是否有可能从类或函数的实例中构造属性/方法,同时保持跨结构变量的范围?例如:

function Counter() {
  this.state = {count: 0}
  this.update = (fragment) => {
    this.state = Object.assign({}, this.state, fragment)
  }
  this.increment = () => {
    this.update({count: this.state.count + 1})
  }
  this.decrement = () => {
    this.update({count: this.state.count - 1})
  }
}

const counter = new Counter

const {
  state,
  increment,
  decrement
} = counter

console.log(state)
increment()
console.log(state)
decrement ()
console.log(state)

JS Bin

每个console.log的结果都是相同的:{count: 0}因为它为每个变量创建了一个新实例和新范围。

这是故意的吗?我是以错误的方式接近这个吗? (我正在创建一个库,我假设有人会尝试以这种方式使用它,所以我想让它工作)

1 个答案:

答案 0 :(得分:3)

在你的例子中,解构desugars到类似

的东西
const state = counter.state;

counter.state分配新值不会神奇地更新state的值。解构并没有改变它。

相关问题