Availability: |
| ||||||||
JavaScript syntax: | - | with( anObject ) { someCode }; | |||||||
Argument list: | someCode | Some code to execute with the enhanced scope chain | |||||||
anObject | A reference to an object to add to the scope chain |
This statement is provided as a convenience mechanism to simplify your script code and save time and trouble.
When a statement executes, your line of script is running in one context or another. Each context is created and destroyed as functions are called and exit respectively. The contexts are added to an inheritance chain, which allows variables to be shared globally or locally.
The with keyword adds an object to the front of the scope chain for the current execution context. This saves you having to describe the full object reference since it is placed in the scope chain and always available and implicitly provided by JavaScript when resolving references to identifiers.
The code in the statement block is then executed while this augmented scope chain is in place. The object that is added to the scope chain is computed by the expression value in parentheses.
When the statement block is executed, the scope chain is restored to its original condition. This happens regardless of how the statement block is completed. Although the ECMA standard is ambiguous on this point, the implication is that a break might be appropriate in this context. A continue or return in the statement block would be inappropriate unless perhaps the with() construct is used within an iterator or function. Because of this ambiguity, you may find this behaves differently according to the implementation you are using.
The with statement can save you effort typing object names over and over again.
Even though it is very convenient, it is considered somewhat bad form to use this construct. The code is hard to optimize inside the interpreter, which means it will likely run more slowly. Functions and variables instantiated inside a with block do not behave consistently, so it is recommended that you avoid using this construct.
// Create a new object var myObject = new Object; // Add a property containing another object myObject.itsObject = new Object; // Add a property to that object myObject.itsObject.someProperty = "String text"; // Now enhance the scope chain with(myObject.itsObject) { document.write(someProperty); }
See also: | Identifier, Identifier resolution, Scope chain, Statement |
ECMA 262 edition 2 - section - 10.1.4
ECMA 262 edition 2 - section - 12.10
ECMA 262 edition 3 - section - 10.1.4
ECMA 262 edition 3 - section - 12.10
Wrox Instant JavaScript - page - 35
Prev | Home | Next |
Windows Script Host | Up | WML |
JavaScript Programmer's Reference, Cliff Wootton Wrox Press (www.wrox.com) Join the Wrox JavaScript forum at p2p.wrox.com Please report problems to support@wrox.com © 2001 Wrox Press. All Rights Reserved. Terms and conditions. |