with 中的哪些变量对象语句被绑定?

To which variable object statements inside with are bind?

function buildUrl() {
  var qs = "?debug=true";
  with(location){
    var url = href + qs;
  }
  return url;
}
buildUrl(); // it will work. WHY?

我正在研究 N. Zakas 的 "Professional JavaScript for Web Developers",我发现了这个片段。根据我的理解,with 是一个通过将 location 对象推到前面来扩充作用域链的语句。

似乎 url 局部变量被分配给了一个函数激活对象。为什么不分配给 location

不推荐使用 with 语句

通常不鼓励使用 with 语句。 严格模式禁止:

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);
}

请使用短名称的临时变量。

var b = foo.bar.baz; 
console.log("Hello "+b.first+" "+b.last);

with 添加参数 location 用于查找目的,但您的 var url 仍被提升到包含函数 - 即 buildUrl,因为您正在创建变量,不查找。

但是,你应该完全避免withsee the statement on MDN