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

后端 未结 4 710
梦谈多话
梦谈多话 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:09

    This fails because you're missing the location context (the function's this), when passing it your way. You would have to bind the context, before you can use it like this, for example with the underscore.js bind method

    var boundReload = _.bind(window.location.reload, window.location);
    setTimeout(boundReload, 500)
    

    It's the same with any other function that is usually called from it's containing object like console.log

    0 讨论(0)
  • 2020-11-28 10:12

    Because this must be bound to location when you call reload. It's same as trying:

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

    this would be window in non-strict mode and undefined in strict mode which are both invalid.

    in non-old browsers you can do instead:

    reload.call( location )

    or in your example:

    setTimeout( window.location.reload.bind( window.location ), 1000 )

    Older IEs don't support explicit binding on host objects though.

    You also get this for some native methods which are not generic such as:

    var a = function(){}.toString;
    a();
    TypeError: Function.prototype.toString is not generic
    

    Some are generic:

    var fakeArray = {0:1,1:2,length:2};
    fakeArray.join = [].join;
    fakeArray.join( " " );
    "1 2"
    
    0 讨论(0)
  • 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
    0 讨论(0)
  • 2020-11-28 10:26

    There is another way of doing this, pretty simple, and no need of doing extra steps, bindings or stuff like that. When you use arrow functions instead of common functions in JS, the this context is included. So you could just as easily do the following:

    setTimeout(() => window.location.reload(), 250);
    
    0 讨论(0)
提交回复
热议问题