[英]window.onload not firing for function named onload
Today I ran into a strange problem: 今天我遇到一个奇怪的问题:
window.onload
does not seem to fire when referencing a function called onload
. 引用名为
onload
的函数时,似乎不会触发window.onload
。
I have never noticed this before: 我以前从未注意到:
Test 1 : 测试1 :
window.onload=onload; function onload(){ console.log('event fired'); }
Test 2 : 测试2 :
window.onload=onload2; function onload2(){ console.log('event fired'); }
Why doesn't the first code work? 为什么第一个代码不起作用?
Onload是您无法覆盖的预定义/预构建的javascript函数。
That happens because of the scope. 那是因为范围。 If you leave out
window.
如果您不在
window.
in your second example, the alert will still fire . 在第二个示例中, 警报仍将触发 。 In the first example, you are overwriting the
window.onload
function. 在第一个示例中,您将覆盖
window.onload
函数。
If you do it that way you will be overwriting the onload predefined function built from javascript. 如果这样做,将覆盖由javascript构建的onload预定义函数。 But if you want to give the name onload to your function you can do it this way.
但是,如果要将名称onload赋予函数,则可以使用这种方法。
function onload() { alert("Page is loaded"); }
<!DOCTYPE html> <html> <body onload="onload()"> <h1>Hello World!</h1> </body> </html>
The problem here is that in web browsers, the window
is set as the global object. 这里的问题是,在Web浏览器中,
window
被设置为全局对象。 This means that window.onload
and onload
are referring to the same property. 这意味着
window.onload
和onload
引用相同的属性。
console.log(window.onload === onload); // true
So what you are essentially doing is 因此,您实际上要做的是
window.onload = window.onload;
which doesn't change anything. 不会改变任何东西。
If you want a function with the same name, you can put it in an IIFE (or in any function for that matter). 如果要使用同名的函数,可以将其放在IIFE中 (或与此相关的任何函数中)。 In that case the function you define will not be put in the global scope and therefore it wont conflict with the existing
window.onload
. 在这种情况下,您定义的函数将不会放入全局范围,因此不会与现有的
window.onload
冲突。
(function() { window.onload = onload; function onload() { console.log('event fired'); } })();
If you don't necessarily value the function name you can, next to changing the function name, also assign the function directly to the onload
like so: 如果不必一定要赋值函数名称,则可以在更改函数名称旁边将函数直接分配给
onload
如下所示:
window.onload = function() { console.log('event fired'); };
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.