简体   繁体   中英

how to bind method to variable inside constructor method in class

while I'm retrieving data using getValue() and binding its value to this.itemList variable in the constructor method inside the class it returns an empty array however there are data in local storage how is the right way to do that?.

 class UI { constructor() { this.storageBudget = UI.getValue(this.BUDGET_LOCAL_STORAGE); this.itemList = JSON.parse(UI.getValue(this.EXPENSE_LOCAL_STORAGE)) || []; this.itemID = 0; this.BUDGET_LOCAL_STORAGE = 'BUDGET_LOCAL_STORAGE'; this.EXPENSE_LOCAL_STORAGE = 'EXPENSE_LOCAL_STORAGE'; } static save(key, value) { localStorage.setItem(key, value); } static getValue(key) { return localStorage.getItem(key); } }

You're using this.BUDGET_LOCAL_STORAGE and this.EXPENSE_LOCAL_STORAGE in the calls to UI.getValue() before you set them. So set those properties before you try to use them.

 class UI { constructor() { this.BUDGET_LOCAL_STORAGE = 'BUDGET_LOCAL_STORAGE'; this.EXPENSE_LOCAL_STORAGE = 'EXPENSE_LOCAL_STORAGE'; this.storageBudget = UI.getValue(this.BUDGET_LOCAL_STORAGE); this.itemList = JSON.parse(UI.getValue(this.EXPENSE_LOCAL_STORAGE)) || []; this.itemID = 0; } static save(key, value) { localStorage.setItem(key, value); } static getValue(key) { return localStorage.getItem(key); } }

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM