Tuesday, July 16, 2013

JavaScript Jargon - Scope Chain, Execution Context and Activation Object

In JavaScript every function is represented as an object - an instance of the JavaScript Function. Like any other object, it also has some properties which can be accessed programmatically and  few which are used only by the JavaScript engines. One of the properties is [[Scope]] which is available only for the engines.
This internal [[Scope]] property is a collection of objects which represents the scope/environment in with the function is defined. The collection of objects, which determines the data which the function can access, is known as function's Scope Chain. Each object in the Scope Chain is called as Variable Object. A Variable Object holds the variables, in the form of key-value pair, which a function can access.
Let's understand it better with the following example -

function multiply(arg1, arg2){
     var result = arg1 * arg2;
    return result;
}

In this case as soon as the function is created, it's Scope Chain is initialized with a variable object - Global Object. A Global Object is a collection of data, available outside the scope of the function, which the function can access, like - window, document, navigator etc..
At the time of function execution, an internal object  - Execution Context, is created. Execution Context represents the environment in which the function is executed. Once the execution is completed, this object is destroyed. Execution Context is created per execution. Therefore if the same function is executed multiple times, multiple Execution Context objects are created.
Execution Context object also has it's own Scope Chain object which is initialized with the data present in the function's [[Scope]] object. Later a new object - Activation Object, is created and pushed on top of the Global Object in the Execution Context's Scope Chain.
The internal Activation Object holds data specific to the function - local variable/s, named argument/s, argument[] and this. Again this object is destroyed once the function execution is completed. .


No comments: