/What means keyword WITH in JS?/
with(object)command;
with
allows you to create a block bounded to an object scope. Something like:
var obj = {a: 1,b: 2, c: 3};
// more "tedious" to repeat "obj"
obj.a = 2;
obj.b = 3;
obj.c = 4;
// "easier" short-hand
with (obj) {
a = 3;
b = 4;
c = 5;
}
But this creates lots of problems. Its problems are well explained in chapter 2 of Kyle Sympson's book "Scope & Closures" of the "You don't know JS". I recommend you to read it. Don't use it, if you don't know very well what you're doing or this could be hard to debug.
Allows properties of an object to be treated as local variables within a statement.
var obj = { text: "testing" };
with (obj) {
console.log(text);
}
instead of
var obj = { text: "testing" };
console.log(obj.text);
This is deprecated and is forbidden in strict mode.
Extended chains are probably what we love more about JavaScript libraries ...
$("stuff")
.more()
.again()
.somethingElse()
;
but for some sadistic reason we decided that we don't like native extended chains in our code ...
with(stuff){
more()
again()
somethingElse()
};
Every time I say that with statement has nothing bad, somebody perpetually points out this bloody post ... OK, from Yahoo! ... so what? Honestly, I could post thousands of bad examples and point my finger into this or that library, function, method, evaluation, etc etc ... it's like the myth eval is evil ... so how come one of the first one to talk about evil is using eval to speed up code interpretation? Easy: there are cases and cases!
I give you the most basic example ever, something happened in twitter few minutes ago, OK? I wanna use the smallest amount of characters to obtain a script injection ... right?
with(document.documentElement)
insertBefore(
document.createElement("script"),
firstChild
)
.text = "alert(1)"
;
Elegant, memory aware (no variables declarations, no need to create a closure), compact, efficient, cross-browser ... where are "JavaScripters" that used with to assign variables here?
In any case, I'd love to see who is able to produce a code smaller than the precedent example taking care about removing any trace of that operation in the current scope.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/with
"JavaScript looks up an unqualified name by searching a scope chain associated with the execution context of the script or function containing that unqualified name. 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. Otherwise a ReferenceError is thrown."
obj = {'when': 'now'}
with (obj) {
console.log(when)
}