📜 ⬆️ ⬇️

Operator with and why it should not be used

This article explains how to work with JavaScript and why it is not recommended.

Operator syntax with


with (object) statement 

with creates a new scope scope and presents the properties of the object as local expression statements. Example (brackets are not required for one expression, but they are recommended to be used):
 with({ first: "John" }) { console.log("Hello " + first); } // Hello John 

There is a similar object whose properties are simultaneously global variables - this object is called global (in browsers it is a window). But unlike the global object, the variables that are declared in the with statement (statement block) are not added to the “object” object, but are leaked into the external scope and exist further.
 with({}) { var x = "abc"; } console.log(x) // 'abc' 

The with statement is deprecated.


Using a with expression is not desirable. Its use is prohibited in Strict Mode :
 function foo() { "use strict"; with({}); } // SyntaxError: strict mode code may not contain 'with' statements 

What to replace with:
 with(foo.bar.baz) { console.log("Hello "+first+" "+last); } 

Instead of passing the variable in with, use the short name:
 var b = foo.bar.baz; console.log("Hello "+b.first+" "+b.last); 

If you do not wish to declare a temporary variable in your scope, use IIFE :
 (function() { var b = foo.bar.baz; console.log("Hello "+b.first+" "+b.last); }()); 

You can also send this object as a IIFE parameter:
 (function(b) { console.log("Hello "+b.first+" "+b.last); }(foo.bar.baz)); 

So why with is bad


To understand why with is obsolete, let's look at an example and see how a function argument changes its behavior. Here is the function:
 function foo(arg) { with(arg) { console.log("arg: " + arg) } } 

Run the function with different parameters:
 foo("Hello"); // arg: Hello -  arg foo({}); // arg: [object Object] -  arg foo({ arg: "Hello" }); // arg: Hello -  arg.arg! 

There are two reasons why with is obsolete:
Performance : the with statement cannot be optimized automatically, because it is not known in advance where the arg: will refer to a real variable or a property of a variable inside with. This may change with each call.

Security : it is impossible to determine where a variable refers to by looking at its surroundings (its lexical environment). According to Brendan, Eich precisely because of this with is considered obsolete, and not because of performance considerations.

')

Source: https://habr.com/ru/post/120364/


All Articles