[英]Why can't I empty array within class with bound method?
下面是Example
class,其中包含两个绑定方法reset
和addItem
。 我希望这段代码记录0
但它记录了4
。 我很好奇为什么会这样,以及是否有办法让它按我期望的方式工作。
class Example { array = [] constructor () { this.reset = this.reset.bind(this) this.addItem = this.addItem.bind(this) } reset () { this.array = [] } addItem () { this.array.push('hello') } } const {array, reset, addItem} = new Example() addItem() addItem() addItem() addItem() reset() console.log(array.length)
在这一行
const {array, reset, addItem} = new Example()
当实例化 object 时,您正在提取array
、 reset
和addItem
的当前引用。 如果您稍后重新分配 object 的其中一个属性,之前的引用将不会自行更改以指向新值。 出于同样的原因,以下记录 1,而不是 2。
const obj = { num: 1 }; let { num } = obj; obj.num = 2; console.log(num);
对于您的代码,您可以创建一个名为getArray
的方法
class Example { array = [] constructor () { this.reset = this.reset.bind(this) this.addItem = this.addItem.bind(this) } getArray = () => this.array; reset () { this.array = [] } addItem () { this.array.push('hello') } } const {getArray, reset, addItem} = new Example() addItem() addItem() addItem() addItem() reset() console.log(getArray().length)
或者您可以改变数组而不是在reset
中重新分配它。
class Example { array = [] constructor () { this.reset = this.reset.bind(this) this.addItem = this.addItem.bind(this) } reset () { this.array.length = 0; } addItem () { this.array.push('hello') } } const {array, reset, addItem} = new Example() addItem() addItem() addItem() addItem() reset() console.log(array.length)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.