问题描述
|
我正在Chrome控制台中尝试以下测验:测验
我不明白为什么此代码的答案是2
(function f(){
function f(){ return 1; }
return f();
function f(){ return 2; }
})();
在line1ѭ行中叫哪个f?
功能的顺序是什么?
解决方法
函数是有作用域的(因此,具有相同名称的函数中的函数仅在内部调用时才会覆盖外部函数)并进行提升(因此,它们在代码顺序中的显示位置无关紧要),最后一个覆盖第一个。
, 问题和答案是很多人称为call2ѭ。
像这样的函数声明在执行时不会在
parsing time
处解释。简而言之,第二个函数声明f()
覆盖第一个函数声明,因此返回值为2
。
function declarations
和scoped variables
起吊(用var
声明)。例如:
(function() {
if( false ) {
var hello = 10;
}
console.log( hello );
}());
console.log将返回“ 10”,并且不会在此处引发异常。即使从未遇到if statement
,也已在function context
中声明了变量。
, 在编译时,将在f范围内悬挂声明。在运行时看起来像这样:
(function f(){
function f(){ return 1; }
function f(){ return 2; }
return f();
})();
jAndy示例如下所示:
(function() {
var hello;
if( false ) {
hello = 10;
}
console.log( hello );
}());