with ... (Statement)

Adds an object to the front of the scope chain for use in the following block of script code.

Availability:

ECMAScript edition - 2
JavaScript - 1.0
JScript - 1.0
Internet Explorer - 3.02
Netscape - 2.0
Netscape Enterprise Server - 2.0
Opera - 3.0
JavaScript syntax:-with( anObject ) { someCode };
Argument list:someCodeSome code to execute with the enhanced scope chain
anObjectA 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.

Warnings:

Example code:

   // 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

Cross-references:

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