[英]Why can't I empty array within class with bound method?
Below I have the Example
class with two bound methods reset
and addItem
.下面是Example
class,其中包含两个绑定方法reset
和addItem
。 I'd expected this code to log 0
but instead it logs 4
.我希望这段代码记录0
但它记录了4
。 I'm curious as to why this is happening, and if there is a way to have it work the way I'd expect.我很好奇为什么会这样,以及是否有办法让它按我期望的方式工作。
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)
In this line在这一行
const {array, reset, addItem} = new Example()
you're extracting the current references of array
, reset
, and addItem
when the object is instantiated.当实例化 object 时,您正在提取array
、 reset
和addItem
的当前引用。 If you reassign one of the properties of the object later, the previous references will not change by themselves to point to the new value.如果您稍后重新分配 object 的其中一个属性,之前的引用将不会自行更改以指向新值。 For the same reason, the following logs 1, not 2.出于同样的原因,以下记录 1,而不是 2。
const obj = { num: 1 }; let { num } = obj; obj.num = 2; console.log(num);
For your code, you could make a method named getArray
对于您的代码,您可以创建一个名为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)
Or you could mutate the array instead of reassigning it in reset
.或者您可以改变数组而不是在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.