javascript中变量的范围是什么?它们在函数内部的作用域与在函数外部的作用域相同吗?或者这有关系吗?此外,如果变量是全局定义的,那么变量存储在哪里?


当前回答

全球范围:

全球变量就像全球明星(成龙、纳尔逊·曼德拉)。您可以从应用程序的任何部分访问它们(获取或设置值)。全球功能就像全球活动(新年、圣诞节)。您可以从应用程序的任何部分执行(调用)它们。

//global variable
var a = 2;

//global function
function b(){
   console.log(a);  //access global variable
}

本地范围:

如果你在美国,你可能会认识金·卡戴珊(Kim Kardashian),她是臭名昭著的名人(她以某种方式制作了小报)。但美国以外的人不会认出她。她是当地的明星,与她的领地息息相关。

局部变量就像局部恒星。您只能在范围内访问它们(获取或设置值)。本地函数就像本地事件一样,只能在该范围内执行(庆祝)。如果您想从作用域之外访问它们,将出现引用错误

function b(){
   var d = 21; //local variable
   console.log(d);

   function dog(){  console.log(a); }
     dog(); //execute local function
}

 console.log(d); //ReferenceError: dddddd is not defined    

查看本文以深入了解范围

其他回答

在JavaScript中,有两种类型的作用域:

本地范围全局范围

Below函数有一个局部范围变量carName。这个变量不能从函数外部访问。

function myFunction() {
    var carName = "Volvo";
    alert(carName);
    // code here can use carName
}

Below Class有一个全局范围变量carName。这个变量可以从类中的任何地方访问。

class {

    var carName = " Volvo";

    // code here can use carName

    function myFunction() {
        alert(carName);
        // code here can use carName 
    }
}

(函数foo(){console.log(foo)})();console.log(foo类型);//未定义,因为“foo”的作用域是它自己的表达式//但是,像这样(函数foo(){console.log('1:',foo)//函数foofoo=100console.log('2:',foo)//函数foo,不是100,为什么?})()

老式JavaScript

传统上,JavaScript实际上只有两种类型的作用域:

全局范围:从应用程序开始,变量在整个应用程序中都是已知的(*)函数作用域:变量在声明它们的函数中是已知的,从函数开始(*)

我不会详细说明这一点,因为已经有许多其他答案可以解释这一差异。


现代JavaScript

最新的JavaScript规范现在还允许第三个范围:

块作用域:标识符从其声明的作用域的顶部开始“已知”,但在其声明的行之后才能分配或取消引用(读取)。这一过渡时期被称为“时间死区”


如何创建块范围变量?

传统上,您可以这样创建变量:

var myVariable = "Some text";

块范围变量的创建方式如下:

let myVariable = "Some text";

那么,功能范围和块范围之间的区别是什么?

要了解功能范围和块范围之间的区别,请考虑以下代码:

// i IS NOT known here
// j IS NOT known here
// k IS known here, but undefined
// l IS NOT known here

function loop(arr) {
    // i IS known here, but undefined
    // j IS NOT known here
    // k IS known here, but has a value only the second time loop is called
    // l IS NOT known here

    for( var i = 0; i < arr.length; i++ ) {
        // i IS known here, and has a value
        // j IS NOT known here
        // k IS known here, but has a value only the second time loop is called
        // l IS NOT known here
    };

    // i IS known here, and has a value
    // j IS NOT known here
    // k IS known here, but has a value only the second time loop is called
    // l IS NOT known here

    for( let j = 0; j < arr.length; j++ ) {
        // i IS known here, and has a value
        // j IS known here, and has a value
        // k IS known here, but has a value only the second time loop is called
        // l IS NOT known here
    };

    // i IS known here, and has a value
    // j IS NOT known here
    // k IS known here, but has a value only the second time loop is called
    // l IS NOT known here
}

loop([1,2,3,4]);

for( var k = 0; k < arr.length; k++ ) {
    // i IS NOT known here
    // j IS NOT known here
    // k IS known here, and has a value
    // l IS NOT known here
};

for( let l = 0; l < arr.length; l++ ) {
    // i IS NOT known here
    // j IS NOT known here
    // k IS known here, and has a value
    // l IS known here, and has a value
};

loop([1,2,3,4]);

// i IS NOT known here
// j IS NOT known here
// k IS known here, and has a value
// l IS NOT known here

在这里,我们可以看到变量j只在first for循环中知道,而在前后都不知道。然而,我们的变量i在整个函数中是已知的。

此外,考虑到块范围的变量在声明之前是未知的,因为它们没有被提升。也不允许在同一块内重新声明同一块范围内的变量。这使得块作用域变量比全局或函数作用域变量更不容易出错,这些变量被提升,在多个声明的情况下不会产生任何错误。


现在使用块范围变量安全吗?

今天使用它是否安全取决于您的环境:

如果您正在编写服务器端JavaScript代码(Node.js),则可以安全地使用let语句。如果您正在编写客户端JavaScript代码并使用基于浏览器的转译器(如Traceur或babel standalone),则可以安全地使用let语句,但是您的代码在性能方面可能不是最佳的。如果您正在编写客户端JavaScript代码并使用基于节点的转译器(如traceur shell脚本或Babel),则可以安全地使用let语句。而且,由于您的浏览器将只知道转译的代码,因此性能缺陷应该受到限制。如果您正在编写客户端JavaScript代码,而不使用转译器,则需要考虑浏览器支持。以下是一些根本不支持let的浏览器:Internet explorer 10及以下Firefox 43及以下Safari 9及以下Android浏览器4及以下版本Opera 27及以下Chome 40及以下Opera Mini和黑莓浏览器的任何版本


如何跟踪浏览器支持

有关阅读此答案时哪些浏览器支持let语句的最新概述,请参阅“我可以使用”页面。


(*)全局和函数范围的变量可以在声明之前初始化和使用,因为JavaScript变量被提升。这意味着声明总是位于范围的顶部。

JS中只有函数作用域。不阻止范围!你也可以看到什么在提升。

var global_variable = "global_variable";
var hoisting_variable = "global_hoist";

// Global variables printed
console.log("global_scope: - global_variable: " + global_variable);
console.log("global_scope: - hoisting_variable: " + hoisting_variable);

if (true) {
    // The variable block will be global, on true condition.
    var block = "block";
}
console.log("global_scope: - block: " + block);

function local_function() {
    var local_variable = "local_variable";
    console.log("local_scope: - local_variable: " + local_variable);
    console.log("local_scope: - global_variable: " + global_variable);
    console.log("local_scope: - block: " + block);
    // The hoisting_variable is undefined at the moment.
    console.log("local_scope: - hoisting_variable: " + hoisting_variable);

    var hoisting_variable = "local_hoist";
    // The hoisting_variable is now set as a local one.
    console.log("local_scope: - hoisting_variable: " + hoisting_variable);
}

local_function();

// No variable in a separate function is visible into the global scope.
console.log("global_scope: - local_variable: " + local_variable);

内联处理程序

前端代码编写者经常遇到的一个尚未描述的非常常见的问题是HTML中内联事件处理程序可见的范围,例如

<button onclick="foo()"></button>

on*属性可以引用的变量范围必须是:

全局(工作内联处理程序几乎总是引用全局变量)文档的属性(例如,作为独立变量的querySelector将指向document.querySelector;罕见)处理程序附加到的元素的属性(如上所述;罕见)

否则,当调用处理程序时,将得到ReferenceError。因此,例如,如果内联处理程序引用了在window.onload或$(function){中定义的函数,则引用将失败,因为内联处理程序只能引用全局范围内的变量,而函数不是全局的:

window.addEventListener('DOMContentLoaded',()=>{函数foo(){console.log('运行');}});<button onclick=“foo()”>单击</button>

文档的财产和处理程序附加到的元素的财产也可以作为内联处理程序中的独立变量引用,因为内联处理函数是在两个块中调用的,一个用于文档,另一个用于元素。这些处理程序中变量的作用域链非常不直观,并且一个工作的事件处理程序可能需要一个函数是全局的(并且应该避免不必要的全局污染)。

由于内联处理程序内部的作用域链非常奇怪,而且内联处理程序需要全局污染才能工作,并且内联处理程序在传递参数时有时需要丑陋的字符串转义,因此可能更容易避免它们。相反,使用Javascript(如addEventListener)而不是HTML标记附加事件处理程序。

函数foo(){console.log('运行');}document.querySelector('.my button').addEventListener('click',foo);<button class=“my button”>单击</button>

模块(<script type=“module”>)

另一方面,与在顶层运行的普通<script>标记不同,ES6模块内的代码在其自己的私有范围内运行。在普通<script>标记顶部定义的变量是全局的,因此您可以在其他<script>标签中引用它,如下所示:

<脚本>const foo=“foo”;</script><脚本>console.log(foo);</script>

但是ES6模块的顶层不是全局的。在ES6模块顶部声明的变量仅在该模块内部可见,除非该变量被显式导出,或者除非它被分配给全局对象的属性。

<script type=“module”>const foo=“foo”;</script><脚本>//无法在此处访问foo,因为其他脚本是模块console.log(foo类型);</script>

ES6模块的顶层与普通<script>中顶层IIFE内部的顶层类似。模块可以引用任何全局变量,除非模块为其明确设计,否则任何内容都不能引用模块内部的任何内容。