我需要将 JSON 存储在变量中。我有下一个功能:
retrieve(){
JSON.parse(localStorage.getItem('todos'));
}
我试图将函数的返回值存储在变量中。
this.todos = this.retrieve()
但我得到:
model.js:5 未捕获的类型错误:无法读取未定义的属性“检索”
如果我这样做,它会起作用:
this.todos = JSON.parse(localStorage.getItem('todos'));
为什么会这样?
编辑:完整代码
export default class Model {
constructor(){
this.view = null;
this.todos = this.retrieve();
if(!this.todos || this.todos.length < 1){
this.todos = [
{
id: 0,
title: 'default',
description: 'default',
completed: false,
}
]
this.id = 1;
}
this.id = this.todos[this.todos.length - 1].id + 1;
retrieve(){
return JSON.parse(localStorage.getItem('todos'));
}
}
谢谢大家。
您的类级方法应该在构造函数之外。
localStorage.setItem('todos', JSON.stringify([{id:1},{id:2},{id:3}]))
class Model {
constructor(){
this.view = null;
this.todos = this.retrieve();
if(!this.todos || this.todos.length < 1){
this.todos = [
{
id: 0,
title: 'default',
description: 'default',
completed: false,
}
]
this.id = 1;
}
this.id = this.todos[this.todos.length - 1].id + 1;
}
retrieve(){
return JSON.parse(localStorage.getItem('todos'));
}
}
console.log(new Model());
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句