英文:
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 的文档,这两种格式都应该起作用。谢谢。
这背后的逻辑是什么?你能与我分享一些信息吗?非常感谢
英文:
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
答案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')
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论