JavaScript 变量作用域是什么

JavaScript 变量作用域是什么

在本文中,我们将学习JavaScript的作用域。作用域管理变量的可用性,或者我们也可以说它确定变量的可访问性。

JavaScript中的作用域类型:

  • 块作用域
  • 函数作用域
  • 局部作用域
  • 全局作用域

块作用域: 在早期的JavaScript中只有全局作用域和函数作用域。而ES6引入了两个新的关键字 letconst 提供了块作用域。ECMAScript(ES6)2015是对JavaScript的第二个重大修订。在一个{ }块中声明的变量不能从块外部访问。

let关键字:

示例:

{
 let x = 2;
}
x cannot be used here

var关键字:

示例:

{
 var x = 2;
}
x can be used here

使用var关键字声明的变量无法具有块级作用域,它们可以在{ }块内部声明,并可以从块外部访问。

示例:

HTML

<!DOCTYPE html>
<html>
 
<body>
    <h2 style="color:green">GeeksforGeeks</h2>
    <script>
        function foo() {
            if (true) {
                var x = '1';    // Exist in function scope
                const y = '2';  // Exist in block scope
                let z = '3';    // Exist in block scope
            }
            console.log(x);
            console.log(y);
            console.log(z);
        }
        foo();
    </script>
</body>
 
</html>

输出结果(在控制台中):

1
y is not defined

函数作用域: JavaScript具有函数作用域,每个函数都创建一个新的作用域。在函数内部定义的变量无法从函数外部访问,而在函数内部声明的使用var、let和const关键字声明的变量非常相似。

var关键字:

示例:

function myFunction() {
   var firstName = "Krishna";   // Function Scope
}

假设关键字:

示例:

function myFunction() {
  let firstName = "Krishna";   // Function Scope
}

const 关键词:

示例:

function myFunction() {
   const firstName = "Krishna";   // Function Scope
}

本地范围: 在函数内部声明的变量成为函数的本地变量。本地变量在函数开始时创建,在函数执行时被删除。本地变量具有函数作用域,这意味着它们只能在函数内部访问。

示例:

// This part of code cannot use firstName

function myFunction() {
 let firstName = "Krishna";
 // This part of code can use firstName
}

This part of code cannot use firstName

HTML

<!DOCTYPE html>
<html>
 
<body>
    <h2 style="color:green">
        GeeksforGeeks
    </h2>
 
    <script>
        function foo() {
            var x = '1';
            console.log('inside function: ', x);
        }
 
        foo();          // Inside function: 1
        console.log(x); // Error: x is not defined 
    </script>
</body>
 
</html>

输出(在控制台中):

inside function: 1
x is not defined

全局作用域: 在任何函数之外声明的变量具有全局作用域,全局变量可以从程序中的任何地方访问。类似于函数作用域中使用 varletconst 声明的变量,在块外声明时也是相似的。

let 关键字:

let x = 2;       // Global scope

const 关键字:

const x = 2;     // Global scope

var关键字:

var x = 2;       // Global scope

示例:

HTML

<!DOCTYPE html>
<html>
 
<body>
    <h2 style="color:green">GeeksforGeeks</h2>
    <script>
 
        // Global scope
        var x = '1'
        const y = '2'
        let z = '3'
 
        console.log(x);    // 1
        console.log(y);    // 2
        console.log(z);    // 3
 
        function getNo() {
            console.log(x);   // x is accessible here
            console.log(y);   // y is accessible here
            console.log(z);   // z is accessible here
        }
        getNo();           // 1
    </script>
</body>
 
</html>

输出(在控制台中):

1
2
3
1
2
3

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程