为什么window.location.reload需要包装在function(){}中? [英] Why does window.location.reload need to be wrapped in a function(){}?
问题描述
我写了一些代码来为页面添加一个按钮:
I've written some code to add a button to the page:
var myButt = document.createElement('button');
myButt.onclick = window.location.reload;
myButt.innerText = 'Reload';
document.body.appendChild(myButt);
但它会抛出错误:
TypeError:输入错误
TypeError: Type error
将其包装在一个函数中修复了问题:
Wrapping it in a function fixes the problem:
myButt.onclick = function(){ window.location.reload(); };
但我的问题是为什么前者不起作用?
But my question is why the former doesn't work?
执行 air.trace(typeof(window.location.reload));
输出 function
。
来自高代表用户的答案表明它应该是可能的。它肯定更简洁。
An answer from a high-rep user suggests that it should be possible. It's definitely more succinct.
我正在运行Adobe AIR 3.6(运行Webkit),如果这有所不同。
I am running Adobe AIR 3.6 (which runs Webkit), if that makes a difference.
推荐答案
这个值在使用它时是不正确的。
此
结果是 myButt
当你需要 window.location
。
The this
value is incorrect when using it like that.
this
turns out to be myButt
when you need it to be window.location
.
要修复此(hehe),请将其包装成您已完成的,或者绑定一个新此
值:
To fix this (hehe), either wrap it as you've done, or bind a new this
value to it:
myButt.onclick = window.location.reload.bind(window.location);
我刚测试过,它适用于Firefox 23.0.1。
I just tested that, and it works on Firefox 23.0.1.
为了将来参考,他使用的 Function.prototype.bind
兼容性代码 here 。
For future reference, he was using the Function.prototype.bind
compatibility code found here.
with my上面的代码,他得到了错误
With my code above, he was getting the error
TypeError:在一个具有无效原型
属性的对象上调用instanceof
TypeError: instanceof called on an object with an invalid prototype property
为了解决这个问题,我将该兼容性代码的第18行更改为以下内容:
To fix this, I changed line 18 of that compatibility code to the following:
fNOP.prototype = this.prototype || {};
这样原型设置为空白对象,因为窗口.location.reload
自然没有原型。
This is so that the prototype gets set to a blank object, because window.location.reload
doesn't have a prototype naturally.
这篇关于为什么window.location.reload需要包装在function(){}中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!