Why does [removed].reload need to be wrapped in a

2019-04-10 11:10发布

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);

But it throws an error:

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?

Executing air.trace(typeof(window.location.reload)); outputs function.

An answer from a high-rep user suggests that it should be possible. It's definitely more succinct.

I am running Adobe AIR 3.6 (which runs Webkit), if that makes a difference.

1条回答
我想做一个坏孩纸
2楼-- · 2019-04-10 11:52

The this value is incorrect when using it like that.
this turns out to be myButt when you need it to be window.location.

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);

I just tested that, and it works on Firefox 23.0.1.




For future reference, he was using the Function.prototype.bind compatibility code found here.

With my code above, he was getting the error

TypeError: instanceof called on an object with an invalid prototype property

To fix this, I changed line 18 of that compatibility code to the following:

fNOP.prototype = this.prototype || {};

This is so that the prototype gets set to a blank object, because window.location.reload doesn't have a prototype naturally.

查看更多
登录 后发表回答