问题描述
我希望有人可以向我解释为什么在浏览器中查看HTML时,下面的JavaScript / HTML会显示门#2:
I'm hoping someone can explain to me why the below JavaScript/HTML will show "door #2" when the HTML is viewed in a browser:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script type="text/javascript">
function testprint() {
alert('door #1');
};
window.onload = testprint;
function testprint() {
alert('door #2');
};
testprint = function() {
alert('door #3');
};
</script>
<script type="text/javascript">
function testprint() {
alert('door #4');
};
</script>
</head>
<body>
</body>
</html>
由于只有声明 testprint
发生在 window.onload
设置为 testprint
,我希望 window.onload
导致'门#1'出现。实际上,onload导致'门#2'。请注意,无论是否包含 testprint
的第一个声明,它都会这样做。
Since only the declaration testprint
occurs before window.onload
is set to testprint
, I would expect window.onload
cause 'door #1' to show up. Actually, onload causes 'door #2'. Note that it will do this whether the first declaration of testprint
is included or not.
第三和第四声明 testprint
使用不同的方式分配函数,我试着看看它是否会覆盖 window.onload
's同样的行为是 testprint
的第二个声明。它没。请注意,如果我将 testprint
的第四个声明移动到第一个脚本块的末尾,它将被 window.onload 。
The third and fourth declaration of
testprint
use different means of assigning the function, I tried this to see if it would override window.onload
's behavior in the same was the second declaration of testprint
does. It did not. Note that if I move the fourth declaration of testprint
to the end of the first script block it would be called by window.onload
.
推荐答案
函数声明是提升的主题,它们在解析时进行评估,通过提升意味着它们可用到声明它们的整个范围,例如:
Function declarations are subject of hoisting, and they are evaluated at parse time, by hoisting means that they are available to the entire scope in where they were declared, for example:
foo(); // alerts foo
foo = function () { alert('bar')};
function foo () { alert('foo');}
foo(); // alerts bar
第一次拨打
foo
将执行函数声明,因为在解析时它可用,第二次调用 foo
将执行在运行时声明的函数表达式。
The first call to
foo
will execute the function declaration, because at parse time it was made available, the second call of foo
will execute the function expression, declared at run-time.
有关函数表达式之间差异的更详细讨论和函数声明,检查和。
For a more detailed discussion about the differences between function expressions and function declarations, check this question and this article.
这篇关于在声明之前引用JavaScript值 - 有人可以解释这一点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!