why doesn't the onload event binds the `this` variable as expected?
does anyone knows why doesn't the onload event binds the this
variable as expected?
Like in this test script, onkeydown gi开发者_开发知识库ves us true (this
is working fine) but onload gives us false (this
now points to window.. wth?):
<!DOCTYPE html>
<html><head>
<script>
function f(t){
alert(t===document.body);
}
</script>
</head><body onkeydown="f(this);" onload="f(this);">
</body></html>
See the documentation:
HTMLBodyElement.onload
Exposes the window.onload event handler to call when the window gains focus.
Note that this handler is triggered when the event reaches the window, not the body element. Use
addEventListener()
to attach an event listener to the body element.
The important part is this handler is triggered when the event reaches the window. The handler is executed in the context of the window
and not the body
.
FWIW, alert(window.onload === document.body.onload);
will yield true
.
精彩评论