02. Environment Object

Every execution context has a so-called Variable Object also called Environment associated with it. Similarly to execution context, Variable object is an abstract entity, a mechanism to describe variable instantiation. Variables and functions declared in a execution context are actually added as properties of this Variable object.

Global Code

When control enters execution context for Global code, a Global object is used as a Variable object. This is precisely why variables or functions declared globally become properties of a Global object:

/* remember that `this` refers to global object when in global scope */
var GLOBAL_OBJECT = this;

var foo = 1;
GLOBAL_OBJECT.foo; // 1
foo === GLOBAL_OBJECT.foo; // true

function bar() {}
typeof GLOBAL_OBJECT.bar; // "function"
GLOBAL_OBJECT.bar === bar; // true

Module code

Every module in JS forms its own Module Variable Object. All declaration done in module become local for this module.

Module can export it's own declarations and import declarations exported from other modules.

Module Variable Object created only once when module loaded for a first time.

Function code

All declarations in Function code become properties of Variable object. The only difference is that when in Function code, a Variable object is not a Global object, but a so-called (Function) Activation object.

Activation object is created every time execution context for Function code is entered. Note that Activation object is an internal mechanism and is never really accessible by program code.

Eval code

Finally, variables declared within Eval code are created as properties of calling context’s Variable object. Eval code simply uses Variable object of the execution context that it’s being called within:

var GLOBAL_OBJECT = this;

eval("var foo = 1;");
GLOBAL_OBJECT.foo; // 1

(function() {
  eval("var bar = 1;");
})();

Last updated