【发布时间】:2019-01-15 13:00:08
【问题描述】:
所以我想用这个代码调用一个函数 Local.getThis onload:
class Local {
getThis() {
let that;
if (localStorage.getItem('that') === null) {
that = [];
console.log(that);
localStorage.setItem('that', that);
} else {
that=JSON.parse(localStorage.getItem('that'));
console.log(that);
}
}
// DOM Load Event
document.addEventListener('DOMContentLoaded', Local.getThis)
但是什么都没有发生,没有任何错误。但是当我将“getThis”更改为 STATIC 时,它可以工作(输出:[])。它需要是静态的吗?
附言
设置后 = [];我收到一个错误
'Uncaught SyntaxError: Unexpected end of JSON input
at JSON.parse (<anonymous>)
at HTMLDocument.getThis'
在下一次重新加载时,但我猜这可能是另一个问题。
编辑:
记录错误与localStorage.setItem('that', that);有关,当然应该是localStorage.setItem('that', JSON.stringify(that));
【问题讨论】:
-
我相信您需要先创建该类的一个新实例,然后才能使用其实例方法之一。即,
new Local()在尝试使用getThis之前
标签: javascript methods static-methods domcontentloaded