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 :)
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')