JavaScript:作用域介绍(函数作用域、块作用域)

2025-05-25

JavaScript:作用域介绍(函数作用域、块作用域)

什么是范围?

范围决定了代码区域内变量或其他资源的可见性或可访问性。

全局范围

JavaScript 文档中只有一个全局作用域。所有函数之外的区域都被视为全局作用域,全局作用域内定义的变量可以在任何其他作用域中访问和修改。

//global scope
var fruit = 'apple'
console.log(fruit);        //apple

function getFruit(){
    console.log(fruit);    //fruit is accessible here
}

getFruit();                //apple

Enter fullscreen mode Exit fullscreen mode

本地范围

在函数内部声明的变量将成为函数的局部变量,并被视为在相应的局部作用域内。每个函数都有其自己的作用域。相同的变量可以在不同的函数中使用,因为它们与各自的函数绑定,并且彼此不可见。

//global scope
function foo1(){
    //local scope 1
    function foo2(){
        //local scope 2
    }
}

//global scope
function foo3(){
    //local scope 3
}

//global scope


Enter fullscreen mode Exit fullscreen mode

局部作用域可以分为函数作用域块作用域。 块作用域的概念是在 ECMA Script 6(ES6)中引入的,同时引入了新的变量声明方式—— constlet

函数作用域

在函数中声明变量时,该变量仅在函数内部可见。您无法在函数外部访问它。var用于定义函数范围内可访问变量的关键字。

function foo(){
    var fruit ='apple';
    console.log('inside function: ',fruit);
}

foo();                    //inside function: apple
console.log(fruit);       //error: fruit is not defined 


Enter fullscreen mode Exit fullscreen mode

块作用域

块作用域是指 ifswitch条件或forwhile循环内的区域。一般来说,只要看到{花括号},它就是一个块。在 ES6 中,constlet关键字允许开发者在块作用域内声明变量,这意味着这些变量仅存在于相应的块内。

function foo(){
    if(true){
        var fruit1 = 'apple';        //exist in function scope
        const fruit2 = 'banana';     //exist in block scope
        let fruit3 = 'strawberry';   //exist in block scope

    }
    console.log(fruit1);
    console.log(fruit2);
    console.log(fruit3);
}

foo();
//result:
//apple
//error: fruit2 is not defined
//error: fruit3 is not defined

Enter fullscreen mode Exit fullscreen mode

词汇范围

另外需要提到的一点是词法作用域。词法作用域意味着子作用域可以访问父作用域中定义的变量。子函数在词法上绑定到其父级的执行上下文。

function foo1(){
    var fruit1 = 'apple';        
    const fruit2 = 'banana';     
    let fruit3 = 'strawberry';
    function foo2(){
        console.log(fruit1);
        console.log(fruit2);
        console.log(fruit3);
    }
    foo2();
}

foo1();

//result:
//apple
//banana
//strawberry

Enter fullscreen mode Exit fullscreen mode

有关varletconst的详细比较,请查看JavaScript:var、let、const

文章来源:https://dev.to/mingt/javascript-introduction-to-scope-function-scope-block-scope-d11
PREV
🖥️ 使用 React.js 克隆 Windows 11
NEXT
每个开发者都必须听的 5 个播客 附赠:Last Note 阅读更多