javascript - JavaScript 中的作用域链增强是什么?

标签 javascript

我不明白 javascript 的作用域链增强。 我找到了一个例子,

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

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

最佳答案

首先,在 JavaScript 中,var 的作用域是它出现的函数,而不是它所在的 block 。因此,如果函数(如 if 语句)if 语句内定义的任何 var 范围都将限定在该函数内:

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

foo();

当您位于 with block 内时,您可以指定要使用的“上下文”。因此,就您而言,您正在使用该位置。当你引用一个变量时,它会首先在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 block 中,它将首先尝试 location.qs 并且不会找到名为 qs 的属性,因此它将查看函数作用域并选取您之前定义的变量。

关于javascript - JavaScript 中的作用域链增强是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38771328/

相关文章:

javascript - 如何在 React Native 应用程序中预填充 TextInput?

javascript - 使用js检测浏览器扩展

javascript - 使用 javascript 内联更改颜色

javascript - 如何从 $_COOKIE ["elementValues"] 中提取单个值?

javascript - 错误 TS2339 : Property 'access_token' does not exist angular 2

javascript - Next.js getInitialProps - 动态路由在生产中不起作用

javascript - jQuery 检索 ID

javascript - XHR 0x80004005 (NS_ERROR_FAILURE) 具有非常简单的 HTTP 请求

javascript - 在 javascript 中设置 var _ = 这种不好的做法

javascript - 正则表达式:只有一个下划线实例