Javascript - The with statement
// JavaScript - The evil with statement:
with (objectName) { ... }
The with statement is evil because it adds complexity to the scope chain. If we
use the with statement, we may have to guess where a particular property or
variable is coming from, whether it is coming from the regular scope chain or it
is part of the object that was used with the with statement.
The with statement evaluates an expression, and if that expression is an object,
it is added to the scope chain of the current execution context (in front of
the Activation/Variable object). The "with" statement then executes another
statement (that may itself be a block statement) and then restores the execution
context's scope chain to what it was before.
A function declaration could not be affected by a "with" statement as they
result in the creation of function object during variable instantiation, but a
function expression can be evaluated inside a "with" statement:
var y = {x:5}; // object literal with an x property
function exampleFuncWith() {
var z;
// Add the object referred to by global variable y to the front of the scope chain.
with (y) {
// Evaluate a function expression to create a function object and assign a reference to that
// function object to the local variable z
z = function() {
... // inner function expression body
}
}
}
exampleFuncWith();
When the exampleFuncWith function is called, the resulting execution context
has a scope chain consisting of its Activation object followed by the global
object. The execution of the "with" statement adds the object referred by the
global variable y to the front of that scope chain during the evaluation of the
function expression. The function object created by the evaluation of the
function expression is assigned a "scope" property that corresponds with the
scope of the execution context in which it is created. A scope chain consisting
of object y, followed by the Activation object from the execution context of the
outer function call, followed by the global object.
page revision: 3, last edited: 14 Nov 2016 22:38





