6.18. withIn Chapter 4, we discussed variable scope and the scope chain -- a 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 like address. Despite its occasional convenience, the 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.[22] For these reasons, it is recommended that you avoid the with statement.
Note that there are other, perfectly legitimate ways to save yourself typing. For instance, we could rewrite the previous example as follows: var form = frames[1].document.forms[0]; form.name.value = ""; form.address.value = ""; form.email.value = ""; Copyright © 2003 O'Reilly & Associates. All rights reserved. |
|