The use of the with
keyword produces an error in JavaScript strict mode code. However, that’s not the worst that can be said against
with
.
Using with
allows a short-hand access to an object’s properties - assuming they’re already set. But use with
to access
some property not already set in the object, and suddenly you’re catapulted out of the object scope and into the global scope, creating or overwriting
variables there. Since the effects of with
are entirely dependent on the object passed to it, with
can be dangerously
unpredictable, and should never be used.
Noncompliant Code Example
var x = 'a';
var foo = {
y: 1
}
with (foo) { // Noncompliant
y = 4; // updates foo.y
x = 3; // does NOT add a foo.x property; updates x var in outer scope
}
print(foo.x + " " + x); // shows: undefined 3
Compliant Solution
var x = 'a';
var foo = {
y: 1
}
foo.y = 4;
foo.x = 3;
print(foo.x + " " + x); // shows: 3 a