Why can't I pass “[removed].reload” as an argument to setTimeout?

后端 未结 4 731
梦谈多话
梦谈多话 2020-11-28 09:31

I would love some insight into the error I am seeing in Safari and Chrome with the following line of code:

setTimeout(window.location.reload, 250);

4条回答
  •  孤独总比滥情好
    2020-11-28 10:18

    Because reload() needs window.location as this. In other words - it is a method of window.location. When you say:

    var fun = window.location.reload;
    
    fun();
    

    You are calling reload() function without any this reference (or with implicit window reference).

    This should work:

    setTimeout(window.location.reload.bind(window.location), 250);
    

    The window.location.reload.bind(window.location) part means: take window.location.reload function and return a function that, when called, will use window.location as this reference inside reload().

    See also

    • How can I pass an argument to a function called using setTimeout?
    • Why doesn't console.log work when passed as a parameter to forEach?
    • Preserve 'this' reference in javascript prototype event handler

提交回复
热议问题