1. 怎么理解 JavaScript 的作用域(Scope)?

117 阅读2分钟

怎么理解 JavaScript 的作用域?

关键词:可访问区域(范围)、全局作用域、函数作用域、块级作用域、域内声明、函数、花括号

Keywords: accessible area (range), global scope, function scope, block scope, in-scope declaration, function, curly braces

1 作用域的概念(The Concept Of Scope)

变量的 作用域是,变量在程序中 可被访问的区域(范围)

The scope of a variable is the area (range) within a program where the variable can be accessed.

the scope of a variablethe rangecan be accessed

它分为 全局作用域函数作用域块级作用域。每种作用域规定了,域内声明的 变量 可被访问范围

It is devided into global scope, function scope and block scope. Each scope specifies the range in which the variables declared within it can be accessed.

it is devided intoeach scopes specifiesin which the variables declaredwithin it

2 代码示例(Code Sample)

2.1 全局作用域(Global Scope)

全局作用域是在 JavaScript 中,变量、函数或对象 在整个程序中都可见、可访问 的作用域。

使用 var 在全局作用域中声明的变量,该变量会成为全局变量,并且可以在全局上下文和函数内部访问。该变量会自动成为全局对象 window 的属性。

var globalVar = "I'm global!";

function example() {
    console.log(globalVar); // Accessible here
}
example(); // 输出 "I'm global"

console.log(window.globalLet);  // 输出 "I'm global"

使用 letconst 在全局作用域声明的变量,该变量可以在全局上下文和函数内部访问,但不能在浏览器中作为 window 对象的属性访问。

let globalLet = "I'm global with let";
const globalConst = "I'm global with const";

function example() {
    console.log(globalLet);  // 可访问
    console.log(globalConst); // 可访问
}
example(); // 输出 "I'm global with let" 和 "I'm global with const"

console.log(window.globalLet);  // undefined
console.log(window.globalConst); // undefined

2.2 函数作用域(Function Scope)

function example() {
    var functionVar = "I'm local to this function!";
    console.log(functionVar); // Accessible here
}

console.log(functionVar); // Error: functionVar is not defined

“在函数里面声明的变量,函数外面,访问不到!”

2.3 块级作用域(Block Scope)

{
    let blockVar = "I'm block scoped!";
    console.log(blockVar); // Accessible here
}

console.log(blockVar); // Error: blockVar is not defined

在一个“块”中(就是包在花括号 {}中),使用 let 或者 const 声明的变量,只能在“该块”中被访问。

Variables declared with let or const within a block (defined by {}) are only accessible within that block.

且在,声明变量的最近的花括号 {} 内,可以访问到。

And can be accessed within the nearest curly braces {}.

{
    let outerVar = "I'm outer scoped!";
    { // innerVar 在这个花括号内可以被访问
        let innerVar = "I'm inner scoped!"; // 只能在最近的“块”({})内被访问到,
        console.log(outerVar); // Accessible here
        console.log(innerVar); // Accessible here
    } // innerVar 在这个花括号内可以被访问
    
    console.log(innerVar); // Error: innerVar is not defined 
    // 访问的位置已经在声明它的最近的块的外面,无法访问到!
}