1
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?

Piotrek Hryciuk
  • 785
  • 10
  • 23
  • What is a "function activation object"? What does it mean to 'bind a statement to a variable"? Anyway, `url` is a variable declared as a variable and would never be interpreted as a property of `location`. –  Nov 21 '16 at 11:08
  • @torazaburo http://softwareengineering.stackexchange.com/a/189973 – Piotrek Hryciuk Nov 21 '16 at 11:58

2 Answers2

1

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.

Bardy
  • 2,100
  • 1
  • 13
  • 11
0

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);
locropulenton
  • 4,743
  • 3
  • 32
  • 57
  • This is not a question to the answer. I know that it is deprecated, but I am trying to understand the mechanism. – Piotrek Hryciuk Nov 21 '16 at 10:57
  • 1
    @PiotrekHryciuk Why are you trying to understand the mechanism of an obsolete construct that you cannot even use in a modern environment? Did you pick up this book in the used book pile? Find a new book quick. –  Nov 21 '16 at 11:06
  • @torazaburo got some recommendations? AFAIK this is the most complete book on js to date. – Piotrek Hryciuk Nov 21 '16 at 11:56
  • How could it be the most complete book when the most recent edition is four years old? it refers to ES5 as "new" and refers to ES6 as "what's coming in Harmony". It refers to the application cache which is not only obsoleted by service workers but was deprecated in HTML5.1, etc. etc. As I said. –  Nov 21 '16 at 12:07