然而测试结果是这两份代码是有区别的。
setTimeout(location.reload, 1000);
setTimeout(function(){location.reload();}, 1000);
1 报错
2 成功。
然而这里偏偏是location.reload 会报错,其他正常的不会报错。why ?
setTimeout(location.reload.bind(this), 1000) 就好了。 but 还是 why ?
Copyright 2014-2025 //m.sbmmt.com/ All Rights Reserved | php.cn | 湘ICP备2023035733号
请看这
http://stackoverflow.com/questions/10839989/why-cant-i-pass-window-location-reload-as-an-argument-to-settimeout
理解下面这段代码就明白啦
this的绑定有四种:1.默认绑定 2. 隐式绑定 3.显式绑定 4. new绑定 (《你不知道的js 上卷》)
这个例子不涉及new绑定,那我就逐一解释前三个。
首先
window.location.reload();
或者
var f = function(){ window.location.reload();};
f();
这种明确指出在xx对象上调用xx方法的语句,都算隐式绑定。所绑定的this是方法前的对象。
再比如
var f = window.location.reload;
f();
这种直接调用方法属于默认绑定,this为window。要注意这种写法,f为reload本身,而不是绑定了window.location的reload。
最后
window.location.reload.call(window.location);
或者
var f = window.location.reload.bind(window.location);
f();
都属于显式绑定,this为传入的第一个对象。后者生成显式绑定的闭包,并且它的优先级是最高的,你把它用作隐式绑定或者默认绑定方式调用,仍然是显式绑定。
因为两种情况下,reload绑定的this不同。