`setTimeout` 与本地存储 API(`getItem`/`setItem`)不兼容。

huangapple go评论66阅读模式
英文:

setTimeout not compatible with localStorage API(getItem/setItem)

问题

我很好奇为什么这两个代码表现不同?像 'console.log' 这样的函数在两种方式下都可以工作,而 localStorage API 函数(getItem、setItem)则不起作用。

setTimeout(() => localStorage.setItem('1', '2'), 1000)
// setTimeout(code, delay) 可以工作

setTimeout(localStorage.setItem, 1000, '1', '2')
// setTimeout(functionRef, delay, param1) 不起作用,报错 "Uncaught TypeError: Illegal invocation"

但根据 mozilla 的文档,这两种格式都应该起作用。谢谢。

这背后的逻辑是什么?你能与我分享一些信息吗?非常感谢 `setTimeout` 与本地存储 API(`getItem`/`setItem`)不兼容。

英文:

I am so curious why these two codes behave differently? Functions like 'console.log' would work in both ways, while localStorage API functions(getItem,setItem) does not work.

setTimeout(()=>localStorage.setItem('1','2'),1000)
// setTimeout(code, delay) works

setTimeout(localStorage.setItem,1000,'1','2')
// setTimeout(functionRef, delay, param1) not working, error "Uncaught TypeError: Illegal invocation"

But according to mozilla,these two formats should both work. Thank you.

What is the logic behind it? Could you please share something with me? Thank you so so much `setTimeout` 与本地存储 API(`getItem`/`setItem`)不兼容。

答案1

得分: 1

感谢 @Keith,setTimeout(localStorage.setItem,1000,'1','2') 实际上等同于 setTimeout(function(){...this...},1000,'1','2'),而在单独调用函数 localStorage.setItem 时,this 丢失了。因此,我们需要将 this 绑定回函数。

setTimeout(localStorage.setItem.bind(localStorage), 1000, '1', '2')
英文:

Thanks to @Keith, setTimeout(localStorage.setItem,1000,'1','2') is actually equal to setTimeout(functon(){...this...},1000,'1','2'), while 'this' was lost when the function 'localStorage.setItem' was called separately. So we need to bind 'this' back to the function.

setTimeout(localStorage.setItem.bind(localStorage),1000,'1','2')

huangapple
  • 本文由 发表于 2023年5月30日 02:30:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/76359624.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定