簡體   English   中英

為什么我不能使用綁定方法清空 class 中的數組?

[英]Why can't I empty array within class with bound method?

下面是Example class,其中包含兩個綁定方法resetaddItem 我希望這段代碼記錄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 時,您正在提取arrayresetaddItem當前引用 如果您稍后重新分配 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM