什么是JavaScript中的Scope链增强?

时间:2016-08-04 15:18:43

标签: javascript

我不明白JavaScript的Scope链扩充。 我找到了一个例子,

function buildUrl(){
    var qs = "?debug=true";
    with(location){
    var url = href +qs;
}
    return url;
}

任何人都可以提供任何简单的例子,这对我来说会更有帮助:) 谢谢:) :)

1 个答案:

答案 0 :(得分:2)

首先,在JavaScript中var的作用域是它出现的函数,不是它所在的块。所以如果函数中有一个块(比如if语句)if语句中定义的任何var将作用于函数:

function foo() {
  if (1 === 1) {
    var output = "Something";
  }
  console.log(output);
}

foo();

当您在with块中时,指定要使用的“上下文”。因此,在您的情况下,您正在使用该位置。当您引用变量时,它将首先在location的上下文中查找变量,如果找不到它,它将查看函数范围:

function foo() {
  var notInLocation = "something "; // Not as attribute of location
  var pathname = "something else"; // Is as attribute of location
  // the pathname in the location here seems to be "/js"
  
  with (location) {
    console.log(notInLocation + href); // href is a attribute of location and notInLocation isn't
    console.log(pathname + href); // hred and pathname are both attributes in location
  }
}

foo()

因此,在with块中,它会首先尝试location.qs并且找不到名称为qs的属性,因此它将查看函数范围并获取变量你之前定义的。