Section 6.18. with


6.18. with

In Chapter 4, we discussed variable scope and the scope chaina list of objects that are searched, in order, to perform variable name resolution. The with statement is used to temporarily modify the scope chain. It has the following syntax:

 with (object)     statement 

This statement effectively adds object to the front of the scope chain, executes statement, and then restores the scope chain to its original state.

In practice, you can use the with statement to save yourself a lot of typing. In client-side JavaScript, for example, it is common to work with deeply nested object hierarchies. For instance, you may have to type expressions like this one to access elements of an HTML form:

 frames[1].document.forms[0].address.value 

If you need to access this form a number of times, you can use the with statement to add the form to the scope chain:

 with(frames[1].document.forms[0]) {     // Access form elements directly here. For example:     name.value = "";     address.value = "";     email.value = ""; } 

This reduces the amount of typing you have to do; you no longer need to prefix each form property name with frames[1].document.forms[0]. That object is temporarily part of the scope chain and is automatically searched when JavaScript needs to resolve an identifier such as address.

Despite its occasional convenience, use of the with statement is frowned upon. JavaScript code that uses with is difficult to optimize and may therefore run more slowly than the equivalent code written without the with statement. Furthermore, function definitions and variable initializations within the body of a with statement can have surprising and counterintuitive behavior.[*] For these reasons, it is recommended that you avoid the with statement.

[*] This behavior, and the reasons behind it, are too complicated to explain here.

Note that there are other perfectly legitimate ways to save yourself some typing. For instance, you can rewrite the previous example as follows:

 var form = frames[1].document.forms[0]; form.name.value = ""; form.address.value = ""; form.email.value = ""; 




JavaScript. The Definitive Guide
JavaScript: The Definitive Guide
ISBN: 0596101996
EAN: 2147483647
Year: 2004
Pages: 767

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net