下面是变量范围的一些基本规则在JavaScript:
- 如果与
var
关键字定义,变量是函数作用域。也就是说,该变量的范围是最接近的包含函数,或者如果没有包含函数,则该范围包含在全局上下文中。 实施例:
// globally-scoped variable (no containing function)
var foo = 'bar';
function test() {
// function-scoped variable
var foo2 = 'bar2';
if (true) {
// still function-scoped variable, regardless of the if-block
var foo3 = 'bar3';
}
// see?
console.log(foo3); // --> 'bar3'
}
- 如果与关键字
let
(ES6 +)定义,则变量是块范围的(此行为更类似于大多数其他C家族语法语言)。例如:
// error: top level "let" declarations aren't allowed
let foo = 'bar';
function test() {
// block-scoped variable (function are blocks, too)
let foo2 = 'bar2';
if (true) {
// block-scoped variable (notice the difference
// from the previous example?)
let foo3 = 'bar3';
}
// uh oh?
console.log(foo3); // --> ReferenceError: foo3 is not defined
}
- 如果既不与
var
或let
关键字(例如,foo = bar
)中所定义,则变量的作用域全局上下文。例如:
// globally-scoped variable
foo = 'bar';
function test() {
// also globally-scoped variable (no var or let declaration)
foo2 = 'bar2';
if (true) {
// still a globally-scoped variable
foo3 = 'bar3';
}
}
test();
console.log(foo, foo2, foo3); // 'bar', 'bar2', 'bar3'
在所有这些情况下,函数的变量的范围内定义仍可以访问变量本身(技术上讲你创建一个封闭,作为numOfLayers
和变量词法范围你的addToString
和doAllLayers
函数)。
请注意,范围规则在技术上比这更细微一些,但是您最好在此处阅读更深入的文章。
有什么问题,代码看起来很好。 – atinder
我不确定我是否正确理解,但是您不会在这里传递任何字符串,thisLayer是您传递的对象。 – abs
@atinder - 我只需要更好地理解JavaScript中的范围 –