Which one of several identically named JavaScript functions is actually called?
I'm trying this quiz in the Chrome console: Quiz
I can'开发者_如何学Got understand why the answer for this code is 2
(function f(){
function f(){ return 1; }
return f();
function f(){ return 2; }
})();
Which f is called in this line return f();
?
What is the sequence of the functions?
Functions are scoped (so a function inside an identically named function will override the outside function only when called inside it) and hoisted (so it doesn't matter where they appear in the code order), and the last one overwrites the first one.
The problem and the answer to this is what many people call Hoisting
.
Function declarations like this, are interpretated at parsing time
not while executing. In simple words, the second function declaration f()
overwrites the first one and therefore, the return value is 2
.
Hoisting happens on function declarations
and scoped variables
(declares with var
). For instance:
(function() {
if( false ) {
var hello = 10;
}
console.log( hello );
}());
The console.log will return undefined
and will not throw an exception here. Even if the if statement
is never encountered the variable was declared within the function context
.
At compile time declarations will be hoisted inside f scope. It would look like this at run time:
(function f(){
function f(){ return 1; }
function f(){ return 2; }
return f();
})();
jAndy example would look like this:
(function() {
var hello;
if( false ) {
hello = 10;
}
console.log( hello );
}());
精彩评论