+ 2
Keyword WITH JavaScript
I would like soné example of the word WITH in JavaScript
1 Resposta
+ 2
WITH in js is used to introduce the properties of object as local variables in statement. Examples are listed below.
(the braces are optional for single statements, but it is recommended to add them):
> with({ first: "John" }) { console.log("Hello "+first); }
Hello John
Its intended use is to avoid redundancy when accessing an object several times.
foo.bar.baz.bla = 123;
foo.bar.baz.yadda = "abc";
with turns this into:
with(foo.bar.baz) {
bla = 123;
yadda = "abc";
}
The use of the with statement is generally discouraged. It is forbidden in strict mode:
> function foo() { "use strict"; with({}); }
SyntaxError: strict mode code may not contain 'with' statements
Best practice: Don’t use a with statement.
with(foo.bar.baz) {
console.log("Hello "+first+" "+last);
}
Do use a temporary variable with a short name.
var b = foo.bar.baz;
console.log("Hello "+b.first+" "+b.last);
Hope you got the information and examples.