Javascript named function as an expression

2020-02-06 16:42发布

问题:

Javascript Code

var d = function c() { console.log(c); };
d(); // function c() { console.log(c); }; 
c(); // Reference Error

I understand the concept of variable hoisting where variable declarations and function definitions are hoisted to top of the existing scope. Also function definition in function expressions are not hoisted.

So, above will be

var d;
d = function c() { console.log(c); };
d();
c();

Hence d is a reference to a named function c

  1. on executing d() the function c is executed in global scope, where there is no variable or property named c. But still console manages to log function definition of c.
  2. When I tried c() I got a reference error. [As I Expected]

Case 2 proves that there is no window property named c available So, How did d() manage to print the c's definition on execution?

Does every function have its own definition in its local scope as a property?

回答1:

Yes. A named function expression produces a variable corresponding to the function name within the scope of that function only.

Here's an excellent but lengthy article on the subject: http://kangax.github.com/nfe/

See also the relevant section of the ECMAScript 5 spec. It has a specific note about this.