我在推特上看到了这个,我也无法解释。通过以下两种方式定义 onload
函数:
1) JSFiddle
<html>
<head>
<script>
onload = function(){
alert('this works');
};
</script>
</head>
<body>
</body>
</html>
2) JSFiddle
<html>
<head>
<script>
window.onload = function(){
alert('this works');
};
</script>
</head>
<body>
</body>
</html>
但是当像下面这样定义时,即使它被分配给window.onload
3) JSFiddle
<html>
<head>
<script>
function onload(){
alert('this doesnt work');
};
alert(window.onload); // this shows the definition of above function
</script>
</head>
<body>
</body>
</html>
这是怎么回事?
最佳答案
前两个示例将函数分配给 window.onload
属性(window.
在第一个示例中是隐式的)。 onload
属性实际上属于window
(简称Window
)的原型(prototype)。
第三个变体声明了一个具有相同名称的新本地 函数,并且该函数隐藏了原型(prototype)中的属性。这意味着,当你请求window.onload
时,引擎首先找到本地版本,并放弃查找原型(prototype)链。所以 alert(window.onload);
会提醒您的函数源。但是,要使事件处理程序起作用,必须将其分配给原型(prototype)对象的 onload
属性。
然而,有一些奇怪的事情发生了:当你试图分配一个从 prototype
继承的属性时,它不应该工作,并且应该在对象,从原型(prototype)中隐藏一个(例如 http://jsfiddle.net/ssBt9/ )。但是 window
的行为不同 ( http://jsfiddle.net/asHP7/ ),并且行为甚至可能因浏览器而异。
关于javascript - 解释 javascript 中的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13806958/