所以我想用以下代码调用函数 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 ));
最佳答案
第1部分:this是JavaScript中的保留字,更改参数的名称。
第 2 部分:Local 是一个类,因此要直接从中访问函数,该函数必须是静态的。否则需要先启动一个实例。然后可以从该实例使用该函数。
关于javascript - 如何在 JavaScript 中调用 onload 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54199374/