Reputation: 795
function buildUrl() {
var qs = "?debug=true";
with(location){
var url = href + qs;
}
return url;
}
buildUrl(); // it will work. WHY?
I am working through a "Professional JavaScript for Web Developers" by N. Zakas, and I came across this snippet. From my understanding with
is a statement that augments scope chain by pushing, in this case, location
object to the front.
It seems that url
local variable is assigned to a function activation object. Why isn't it assigned to location
?
Upvotes: 1
Views: 62
Reputation: 2170
with
adds the argument location
for the purposes of lookup, but your var url
is still hoisted to the containing function - i.e. buildUrl
as you are creating a variable, not looking one up.
However, you should completely avoid with
, see the statement on MDN.
Upvotes: 1
Reputation: 4853
The with statement is deprecated
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);
Upvotes: 0