Function Names Defined As Parameters To A Function Call Aren't Hoisted. Why Not?
Solution 1:
Inside a(function b() {});
, the function is a function expression and not a function declaration (only which are hoisted). You might have a look at var functionName = function() {} vs function functionName() {} for the difference.
Solution 2:
EcmaScript §13 (see the paragraph below the NOTE) defines how Function Expressions and Function Declarations are handled.
Function Declarations are instantiated when the EnvironmentRecord is built (§10.5) and thus hoisted, a Function Expression is evaluated later and it's optional Identifier is never visible to the enclosing scope.
As this is a function expression, it's name is not visible to the outer scope. It's the same like
a = function(){}; // valid as it is a function expression
a = functionb(){};// also valid// b is is not accessable here, same as the anonymous function, but a of course is.
both are valid, but b is not visible to the outer scope. Omitting the name in a function declaration however is not valid. The optional Identifier of the function expression is for reference purposes inside the function body (e.g. to enable recursive calls).
Update to your Update:
The reason why the first console.log yields undefined instead of throwing an error is the hoisting (While the instantiation is hoisted the initialisation isn't):
console.log(a); // undefinedvar a = functionb() {};
console.log(a); // function b() {}// equals (hoisted):var a;
console.log(a); // undefined
a = functionb() {};
console.log(a); // function b() {}
Solution 3:
function b()
doesn't exist until the call a(function b() {});
is executed.
JS doesn't search the code for functions, that way. Also, function b() {}
isn't a function declaration, you're merely passing it as a parameter. The only way to access that function would be within function a()
:
functiona() {console.log(arguments[0])}
a(functionb() {});
//function b() {}
However, this does not mean that you can actually call b()
inside a()
, since b()
is defined in the scope of a
's function call, not in the function itself. Basically, the name b
is useless.
Post a Comment for "Function Names Defined As Parameters To A Function Call Aren't Hoisted. Why Not?"