[ Web Proxy ]
URL:
Viewing: https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Statements/with [Back]  [Original]

with - JavaScript | MDN

This page was translated from English by the community. Learn more and join the MDN Web Docs community.

View in English Always switch to English

with

Deprecated

Avoid using this feature in new projects. JavaScript strict mode prohibits the with statement. This feature may be a candidate for removal from web standards or browsers.

Consider using the following features instead: Destructuring.

: with , .. . "Ambiguity Contra" "Description".

with .

In this article

with (expression)
  statement
expression

exrpession statement. .

statement

. , block statement ({ ... }), .

JavaScript unqualified , , , unqualified . 'with' . unqualified , , . ReferenceError.

: with , (strict mode) ECMAScript 5 . , , .

Performance pro & contra

Pro: with , . , 'with', . 'with' . , , .

Contra: with . , , with. , , with , .

Ambiguity contra

Contra: The with statement makes it hard for a human reader or JavaScript compiler to decide whether an unqualified name will be found along the scope chain, and if so, in which object. So given this example:

js
function f(x, o) {
  with (o) {
    console.log(x);
  }
}

Only when f is called is x either found or not, and if found, either in o or (if no such property exists) in f's activation object, where x names the first formal argument. If you forget to define x in the object you pass as the second argument, or if there's some similar bug or confusion, you won't get an error just unexpected results.

Contra: Code using with may not be forward compatible, especially when used with something other than a plain object. Consider this example:

js
function f(foo, values) {
  with (foo) {
    console.log(values);
  }
}

If you call f([1,2,3], obj) in an ECMAScript 5 environment, then the values reference inside the with statement will resolve to obj. However, ECMAScript 6 introduces a values property on Array.prototype (so that it will be available on every array). So, in a JavaScript environment that supports ECMAScript 6, the values reference inside the with statement will resolve to [1,2,3].values.

with

with Math . with PI [cos]](/ru/docs/Web/JavaScript/Reference/Global_Objects/Math/cos) [sin]](/ru/docs/Web/JavaScript/Reference/Global_Objects/Math/sin), . JavaScript Math .

js
var a, x, y;
var r = 10;

with (Math) {
  a = PI * r * r;
  x = r * cos(PI);
  y = r * sin(PI / 2);
}

Specification
ECMAScript 2027 LanguageSpecification
# sec-with-statement


Web Proxy Viewer  |  New URL  |  Original Page