Is with()
part of the native JavaScript library? Which browsers support it?
The 'with' statement adds the given object to the head of this scope chain during the evaluation of its statement body. If an unqualified name used in the body matches a property in the scope chain, then the name is bound to the property and the object containing the property.
Points to Remember : JavaScript a function allows you to define a block of code, give it a name and then execute it as many times as you want. A function can be defined using function keyword and can be executed using () operator.
An IIFE (Immediately Invoked Function Expression) is a JavaScript function that runs as soon as it is defined. The name IIFE is promoted by Ben Alman in his blog.
To call a function inside another function, define the inner function inside the outer function and invoke it. When using the function keyword, the function gets hoisted to the top of the scope and can be called from anywhere inside of the outer function.
It's part of the JavaScript 1.5 specification. So it must be supported by major browser.
Yes it is part of it. Every browser that supports JavaScript 1.5 supports it (that is all major browsers, or grade A).
However, it is not recommended to use the with statement.
Even though I do agree that it should not be used to just avoid declaring another variable (e.g.)
// BAD use of with is to replace this:
// some.expression.with.lots.of.dots.x = 10;
// some.expression.with.lots.of.dots.y = 20;
// with this:
with (some.expression.with.lots.of.dots) {
x = 10;
y = 20;
}
I do think that it has a reasonable use:
// Acceptable use of with is to close over a variable by value.
var functions = [];
for (var i = 0; i < 5; i++) {
with ({ j: i }) {
functions[i] = function() { return j; };
}
}
The other option for the closure is a nested function, which has its advantages, but I find the debug experience being better if using with.
Beware that JavaScript's with
statement should be avoided.
See: with Statement Considered Harmful
Not a part of any native JS spec I've ever seen, and some quick Google-fu yields no result either. Not to say it isn't in there somewhere, but I'd guess that if it exists it's not well documented or supported.
Edit: beaten to the punch by Philippe, and apparently my answer is wrong. I'll leave it here for humility's sake, though. ;)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With