JavaScript: The Definitive Guide, Sixth Editio javaScript权威指南(第6版) pdf 文字版-文字版, javascript电子书, 和javascript 有关的电子书:

5.7.1 with

This section describes the remaining three JavaScript statements—with, debugger, and use strict.

5.7.1 with

In §3.10.3 , we discussed the scope chain—a list of objects that are searched, in order, to perform variable name resolution. The with statement is used to temporarily extend the scope chain. It has the following syntax:

with (object) statement

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

The with statement is forbidden in strict mode (see §5.7.3 ) and should be considered deprecated in non-strict mode: avoid using it whenever possible. JavaScript code that uses with is difficult to optimize and is likely to run more slowly than the equivalent code written without the with statement.

The common use of the with statement is to make it easier to work with deeply nested object hierarchies. In client-side JavaScript, for example, you may have to type expressions like this one to access elements of an HTML form:


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

with(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 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. It is just as simple, of course, to avoid the with statement and write the code above like this:

var f = document.forms[0]; = ""; f.address.value = ""; = "";

Keep in mind that the scope chain is used only when looking up identifiers, not when creating new ones. Consider this code:

with(o) x = 1;

友情链接It题库(| 版权归yishouce.com所有| 友链等可联系|粤ICP备16001685号-1