我不明白 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/