Skip to content Skip to sidebar Skip to footer

Where Is The Immutable Binding Record Of The Identifier In A Named Function Expression Stored In Javascript?

Recently I ran into some interesting facts about named function expressions (NFE). I understand that the function name of an NFE can be accessed within the function body, which mak

Solution 1:

Where is the immutable binding record of the function name stored?

In an extra lexical environment record that you cannot see :-)

How come the function name foo outweigh var foo = 1 when resolved inside NFE?

In fact it doesn't. You can declare a new local var foo in the function scope without any collisions, but if you don't then the free foo variable does resolve to the immutable binding. It does outweigh global foo variables higher in the scope chain, however.

var foo = 1;
(functionfoo() { "use strict";
    var foo = 2;
    console.log(foo); // 2
}());
(functionfoo() { "use strict";
    console.log(foo); // function …
    foo = 2; // Error: Invalid assignment in strict mode
}());

Are their binding records stored in the same lexical environment?

No. Every named function expression is enclosed in an extra lexical environment that has a single, immutable binding for the function's name initialised with the function.

This is described in the Function Definition (§13) section of the spec. While the steps for function declarations and anonymous function expressions basically are "create a new function object with that function body using the current execution context's lexical environment for the Scope", named function expressions are more complicated:

  1. Let funcEnv be the result of calling NewDeclarativeEnvironment passing the running execution context’s Lexical Environment as the argument
  2. Let envRec be funcEnv’s environment record.
  3. Call the CreateImmutableBinding(N) concrete method of envRec passing the Identifier of the function as the argument.
  4. Let closure be the result of creating a new Function object […]. Pass in funcEnv as the Scope.
  5. Call the InitializeImmutableBinding(N,V) concrete method of envRec passing the Identifier of the function and closure as the arguments.
  6. Return closure.

It does construct an extra wrapper environment just for the function expression. In ES6 code with block scopes:

var x = functionfoo(){};
// is equivalent tovar x;
{
    const foo = function() {};
    x = foo;
}
// foo is not in scope here

What's behind the phenomenon that function name foo is accessible inside but invisible outside?

The foo immutable binding is not created in the current execution context's lexical environment, but in the wrapper environment which is only used for the closure around the function expression.

Post a Comment for "Where Is The Immutable Binding Record Of The Identifier In A Named Function Expression Stored In Javascript?"