* fix: replace sh with shell fix replace terminal with shell fix replace node with js fix replace output with shell fix replace cs with csharp fix replace c++ with cpp fix replace c# with csharp fix replace javasctipt with js fix replace syntax with js fix replace unix with shell fix replace linux with shell fix replace java 8 with java fix replace swift4 with swift fix replace react.js with jsx fix replace javascriot with js fix replace javacsript with js fix replace c++ - with cpp fix: corrected various typos fix: replace Algorithm with nothing fix: replace xaml with xml fix: replace solidity with nothing fix: replace c++ with cpp fix: replace txt with shell fix: replace code with json and css fix: replace console with shell
2.0 KiB
title
title |
---|
With |
With
JavaScript's with
statement is a shorthand way to edit several properties on one object. Most developers discourage its usage, with best practice being not to use with
. See Alternatives below for other approaches.
Note: "strict mode"
in ECMAScript 5 forbids usage of with
.
Syntax
with (expression)
statement
Example Usage
In JavaScript, you can individually modify an object's properties as below:
let earth = {};
earth.moons = 1;
earth.continents = 7;
with
gives you a shorthand way to modify the properties on an object:
with (earth) {
moons = 1;
continents = 7;
}
While this example is contrived, you can understand cases of with
better if you use larger objects as below:
earth.continents.australia.geography.ocean = "Pacific";
earth.continents.australia.geography.river = "Murray";
earth.continents.australia.geography.mountain = "Kosciuszko";
Alternatives
You should not use with
, as it has subtle bugs and compatibility issues. A highly recommended approach is to assign the object to a variable, and then to modify the variable's properties. Here is an example using a larger object:
let earth = {
continents: {
australia: {
geography: {}
}
}
};
let geo = earth.continents.australia.geography;
geo.ocean = "Pacific";
geo.river = "Murray";
geo.mountain = "Kosciuszko";
Try It Out
More Information:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/with
https://yuiblog.com/blog/2006/04/11/with-statement-considered-harmful/