Saturday, May 16, 2015

JavaScript Scope Chain

Every function in Javascipt is represented by an object.  Objects are just name-value pairs.  When the value is a function, the name represents a method.  When the function is executed, it is considered as an instance of the function.

The function object contains a [[Scope]] attribute which point to the scope chain used to resolve identifier (variable, properties, function members) when the function executes.  The [[Scope]] points to a scope chain table which in turn points to a variable object.  The variable object contain a list of variables.

When a function is declared, the scope chain is set up pointing to one variable object - the global object which contains global variables such as "window" (the window object representing the browser window and frames within), navigator (represent the browser such as codename, version properties) "document" etc.  When the function is later executed, a variable object (called activation record) is pushed on the top of the scope chain.  The activation object contains the local variable of the function. To resolve a variable, a search was done from the top of the chain down.  Therefore, a local variable of the same name as a global variable will always be used instead in the function.  When the function ends, the activation record will be removed from the scope chain.

To simplify coding, function and variable name can be shorthanded using the with statement.  For example,

function fn() {
    var doc = document;
    link = doc.getElementByTagName("a");

}

Can be shorthanded to

    with (document) {
        link = doc.getElementByTagName("a");
    :

Internally, the with statement will add a variable record on the top of the scope chain with the doc object to quicken resolution.  However, the activation record containing the local variable will be pushed down the scope chain and as a result the resolution overhead will increase.

Similar effect is also achieve with using try..catch block in the code.  The catch statement, when executed, will push an exception object onto the scope chain.

No comments: