在javascript中解释奇怪的行为 [英] Explaining odd behavior in javascript
问题描述
我在Twitter上看到了这个,我也无法解释。以下列两种方式定义 onload
函数有效:
I saw this on twitter and I couldn't explain it either. Defining a onload
function in the following two manner works:
<html>
<head>
<script>
onload = function(){
alert('this works');
};
</script>
</head>
<body>
</body>
</html>
2) JSFiddle
2) JSFiddle
<html>
<head>
<script>
window.onload = function(){
alert('this works');
};
</script>
</head>
<body>
</body>
</html>
但是当定义如下时,它不会工作,即使它被分配到 window.onload
But when defined like the following, it doesn't work even though it is assigned to window.onload
<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
属性实际上属于窗口的原型
(方便地称为窗口
)。
The first two examples assign a function to the window.onload
property (window.
is implicit in the first example). The onload
property actually belongs to the prototype of window
(conveniently called Window
).
第三个变体声明了一个具有相同名称的新 local 函数,该函数会从原型中隐藏属性。这意味着,当您要求 window.onload
时,引擎会首先找到本地版本,并放弃查找原型链。所以 alert(window.onload);
会提醒你的功能源。但是,要使事件处理程序起作用,必须将其分配给原型对象的 onload
属性。
The third variant declares a new local function with the same name, and that function shadows the property from the prototype. This means, when you ask for window.onload
, the engine finds the local version first, and gives up looking up the prototype chain. So alert(window.onload);
does alert your function source. However, for the event handler to work, it would have to be assigned to the prototype object's onload
property.
但是,有一些奇怪的事情:当你尝试分配一个继承自 prototype
的属性时,它应该不起作用,并且一个自己的属性应该是在对象上创建,从原型中隐藏一个(例如 http://jsfiddle.net/ssBt9/ ) 。但窗口
表现不同( http://jsfiddle.net/asHP7/ ),行为甚至可能因浏览器而异。
However, there is something odd going on: when you try to assign to a property that's inherited from the prototype
, it shouldn't work, and an "own" property should be created on the object, shadowing the one from the prototype (e.g. http://jsfiddle.net/ssBt9/). But window
behaves differently (http://jsfiddle.net/asHP7/), and the behavior may even vary depending on the browser.
这篇关于在javascript中解释奇怪的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!