Below I have the Example
class with two bound methods reset
and addItem
. I'd expected this code to log 0
but instead it logs 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. 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. For the same reason, the following logs 1, not 2.
const obj = { num: 1 }; let { num } = obj; obj.num = 2; console.log(num);
For your code, you could make a method named 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
.
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.