Tutorials
Microsoft AJAX
Microsoft AJAX Library - JavaScript Execution Context
var x, this.x, and x
Using the Right ContextIn this section we'll take a peek under the hood of the JavaScript closures and the mechanisms that allow us to create classes, objects, and object members in JavaScript. For most cases, understanding these mechanisms isn't absolutely necessary for writing JavaScript code—so you can skip it if it sounds too advanced.
If, on the contrary, you should be interested in learning more about the JavaScript parser's inner workings, see the more advanced article at http://www.jibbering.com/faq/faq_notes/closures.html" target="_blank" rel="nofollow"
The JavaScript execution context is a concept that explains much of the behavior of JavaScript functions, and of the code samples presented earlier. The execution context represents the environment in which a piece of JavaScript code executes. JavaScript knows of three execution contexts:
Each execution context has an associated scope, which specifies the objects that are accessible to the code executing within that context.
The scope of the global execution context contains the locally defined variables and functions, and the browser's window object. In that context, this is equivalent to window, so you can access, for example, the location property of that object using either this.location or window.location.
The scope of a function execution context contains the function's parameters, the locally defined variables and functions, and the variables and functions in the scope of the calling code. This explains why the getCellCount() function has access to the _rows and _columns variables that are defined in the outer function (Table):
// Table class
function Table (rows, columns)
{
// save parameter values to local variables
var _rows = rows;
var _columns = columns;
// return the number of table cells
this.getCellCount = function()
{
return _rows * _columns;
};
}
The scope of the eval() execution context is identical to the scope of the calling code context. The getCellCount() function from the above code snippet could be written like this, without losing its functionality:
// return the number of table cells
this.getCellCount = function ()
{
return eval(_rows * _columns);
};
Next Page: var x, this.x, and x