从函数调用JSON.parse会返回Undefined



我需要在一个变量中存储一个JSON。我有下一个功能:

retrieve(){
JSON.parse(localStorage.getItem('todos'));
}

我试图将函数的返回值存储在变量中。

this.todos = this.retrieve()

但我得到了:

model.js:5未捕获类型错误:无法读取未定义的属性"retrieve">

如果我改为这样做,它会起作用:

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());

最新更新