2016-11-21 38 views
1
function buildUrl() { 
    var qs = "?debug=true"; 
    with(location){ 
    var url = href + qs; 
    } 
    return url; 
} 
buildUrl(); // it will work. WHY? 

我正在通过N. Zakas的“专业JavaScript for Web Developers”,并且我遇到了这个片段。从我的理解with是一个声明,通过推动,在这种情况下,location对象的前面扩大范围链。里面绑定了哪些变量对象语句?

看来url局部变量被分配给一个函数激活对象。为什么它没有被分配到location

+0

什么是“功能激活对象”? “将语句绑定到变量”意味着什么?无论如何,'url'是一个声明为变量的变量,永远不会被解释为'location'的属性。 – 2016-11-21 11:08:30

+0

@torazaburo http://softwareengineering.stackexchange。 com/a/189973 –

回答

1

with添加参数location进行查找的目的,但你var url仍然悬挂到含有功能 - 即buildUrl为您创建一个变量,而不是找一个。

但是,您应该完全避免with,see the statement on MDN

0

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); 
+0

这不是问题的答案,我知道它已被弃用,但我正在试图理解这种机制。 –

+1

@PiotrekHryciuk为什么你想了解一个过时构造的机制,你甚至不能在现代化的环境中使用?你是否在旧书堆中拿起这本书?快速找到一本新书。 – 2016-11-21 11:06:13

+0

@torazaburo得到了一些建议?AFAIK这是迄今为止最完整的js书。 –