[英]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.