首页 文章

JavaScript中的变量范围是什么?

提问于
浏览
1781

javascript中变量的范围是什么?它们的内部是否与函数外部相同?或者甚至重要吗?此外,如果全局定义变量,那么它们存储在哪里?

25 回答

  • 1

    我的理解是有三个范围:全球范围,全球可用;本地范围,可用于整个功能而不管块;和块范围,仅适用于块,声明或使用它的表达式 . 全局和局部范围用关键字'var'表示,在函数内或外部,块范围用关键字'let'表示 .

    对于那些认为只有全局和局部范围的人,请解释为什么Mozilla会有一整页描述JS中块作用域的细微差别 .

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let

  • 20

    只是为了添加其他答案,范围是所有声明的标识符(变量)的查找列表,并强制执行一组严格的规则,以确定当前执行的代码如何访问它们 . 该查找可以用于分配变量的目的,该变量是LHS(左手侧)参考,或者它可以用于检索其值,即RHS(右手侧)参考 . 这些查找是JavaScript引擎在编译和执行代码时在内部执行的操作 .

    所以从这个角度来看,我认为一张图片可以帮助我在Kyle Simpson的Scopes and Closures电子书中找到:

    引用他的电子书:

    该建筑代表我们程序的嵌套范围规则集 . 无论您身在何处,建筑的第一层代表您当前执行的范围 . 建筑的顶层是全球范围 . 您可以通过查看当前楼层来解决LHS和RHS参考,如果找不到,请将电梯带到下一层,然后查看下一层,依此类推 . 一旦你到达顶层(全球范围),你要么找到你要找的东西,要么找不到 . 但你不得不停下来 .

    值得一提的是,“一旦发现第一场比赛,范围查找就会停止” .

    这个"scope levels"的想法解释了为什么"this"可以用新创建的范围进行更改,如果它是在嵌套函数中查找的话 . 以下链接介绍了所有这些细节,Everything you wanted to know about javascript scope

  • 9

    最初由Brendan Eich设计的JavaScript范围来自HyperCard脚本语言HyperTalk .

    在这种语言中,显示的操作类似于一堆索引卡 . 有一张主卡称为背景 . 它是透明的,可以看作底卡 . 此基卡上的任何内容都与放置在其上的卡共享 . 放在顶部的每张卡都有自己的内容,该内容优先于之前的卡,但如果需要,仍然可以访问先前的卡 .

    这正是JavaScript作用域系统的设计方式 . 它只是有不同的名字 . JavaScript中的卡片称为 Execution ContextsECMA . 这些背景中的每一个都包含三个主要部分 . 变量环境,词法环境和此绑定 . 回到卡片参考,词汇环境包含堆栈中较低位置的所有内容 . 当前上下文位于堆栈的顶部,并且在那里声明的任何内容都将存储在变量环境中 . 在命名冲突的情况下,变量环境将优先 .

    此绑定将指向包含对象 . 有时,范围或执行上下文会在不包含对象更改的情况下发生更改,例如在包含对象可能是 window 的声明函数或构造函数中 .

    每次传输控件时都会创建这些执行上下文 . 当代码开始执行时,控制被转移,这主要是通过函数执行完成的 .

    这就是技术解释 . 在实践中,重要的是要记住在JavaScript中

    • 范围在技术上"Execution Contexts"

    • 上下文形成一堆存储变量的环境

    • 堆栈顶部优先(底部是全局上下文)

    • 每个函数都创建一个执行上下文(但并不总是一个新的绑定)

    将此应用于此页面上的前一个示例之一(5.“Closure”),可以遵循执行上下文的堆栈 . 在此示例中,堆栈中有三个上下文 . 它们由外部上下文,var 6调用的立即调用函数中的上下文以及var 6中立即调用的函数内部返回函数中的上下文定义 .

    i)外在背景 . 它具有a = 1的可变环境
    ii)IIFE上下文,它具有a = 1的词法环境,但a = 6的可变环境优先于堆栈
    iii)返回的函数上下文,它具有a = 6的词法环境,并且是调用时警报中引用的值 .

  • 5

    在EcmaScript5中,主要有两个范围, local scopeglobal scope 但在EcmaScript6中我们主要有三个范围,本地范围,全局范围和一个名为 block scope 的新范围 .

    块范围的示例是: -

    for ( let i = 0; i < 10; i++)
    {
     statement1...
    statement2...// inside this scope we can access the value of i, if we want to access the value of i outside for loop it will give undefined.
    }
    
  • 16

    现代Js,ES6,'const'和'让'

    对于您创建的每个变量,您应该使用块作用域,就像大多数其他主要语言一样 . var 已过时 . 这使您的代码更安全,更易于维护 .

    const 应该用于 95% of cases . 它使得变量引用无法改变 . 数组,对象和DOM节点属性都可以改变,应该是 const .

    let 应该用于任何期望被重新分配的变量 . 这包括在for循环中 . 如果您在初始化之后更改了值,请使用 let .

    块范围意味着变量仅在声明它的括号内可用 . 这扩展到内部范围,包括在范围内创建的匿名函数 .

  • 8

    旧学校JavaScript

    传统上,JavaScript实际上只有两种类型的范围:

    • Global Scope :从应用程序的开始(*)开始,整个应用程序都知道变量

    • Functional Scope :变量在the function中已知,它们是从函数的开头声明的(*)

    我不会详细说明这一点,因为已经有许多其他答案解释了这一点 .


    现代JavaScript

    most recent JavaScript specs现在也允许第三个范围:

    • Block Scope :变量在the block中已知,从声明之后开始声明它们(**)

    如何创建块范围变量?

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

    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 仅在第一个for循环中已知,但不在之前和之后 . 然而,我们的变量 i 在整个函数中是已知的 .

    另外,请考虑块范围变量在声明之前是未知的,因为它们没有被提升 . 您也不允许在同一个块中重新声明相同的块范围变量 . 这使得块范围变量比全局或功能范围变量更不容易出错,这些变量被提升并且在多个声明的情况下不会产生任何错误 .


    今天使用块范围变量是否安全?

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

    • 如果您正在编写服务器端JavaScript代码(Node.js),则可以安全地使用 let 语句 .

    • 如果您正在编写客户端JavaScript代码并使用转换器(如Traceur),则可以安全地使用 let 语句,但是您的代码在性能方面可能不是最优的 .

    • 如果您正在编写客户端JavaScript代码而不使用转换器,则需要考虑浏览器支持 .

    今天,2016年2月23日,这些是一些不支持 let 或只有部分支持的浏览器:

    • Internet explorer 10 及以下(不支持)

    • Firefox 43 及以下(不支持)

    • Safari 9 及以下(不支持)

    • Opera Mini 8 及以下(不支持)

    • Android browser 4 及以下(不支持)

    • Opera 36 及以下(部分支持)

    • Chome 51 及以下(部分支持)


    如何跟踪浏览器支持

    有关在阅读本答案时哪些浏览器支持 let 语句的最新概述,请参阅this Can I Use page .


    (*)全局和功能范围的变量可以在声明之前初始化和使用,因为JavaScript变量是hoisted . 这意味着声明始终位于范围的顶部 .

    (**)未提升块范围变量

  • 59

    ALMOST只有两种类型的JavaScript范围:

    • 每个var声明的范围与最立即封闭的函数相关联

    • 如果var声明没有封闭函数,则为全局范围

    因此,除函数之外的任何块都不会创建新范围 . 这解释了为什么for循环覆盖外部范围变量:

    var i = 10, v = 10;
    for (var i = 0; i < 5; i++) { var v = 5; }
    console.log(i, v);
    // output 5 5
    

    使用函数代替:

    var i = 10, v = 10;
    $.each([0, 1, 2, 3, 4], function(i) { var v = 5; });
    console.log(i,v);
    // output 10 10
    

    在第一个示例中,没有块作用域,因此最初声明的变量被覆盖 . 在第二个示例中,由于函数有一个新的作用域,因此最初声明的变量是SHADOWED,而不是被覆盖 .

    除了以下内容之外,几乎所有您需要知道的JavaScript范围:

    所以你可以看到JavaScript范围实际上非常简单,尽管并不总是直观的 . 有几点需要注意:

    • var声明被提升到范围的顶部 . 这意味着无论var声明发生在何处,对于编译器来说就像var本身发生在顶部一样

    • 组合了同一范围内的多个var声明

    所以这段代码:

    var i = 1;
    function abc() {
      i = 2;
      var i = 3;
    }
    console.log(i);     // outputs 1
    

    相当于:

    var i = 1;
    function abc() {
      var i;     // var declaration moved to the top of the scope
      i = 2;
      i = 3;     // the assignment stays where it is
    }
    console.log(i);
    

    这可能看起来反直觉,但从命令式语言设计师的角度来看,这是有道理的 .

  • 7

    JavaScript中有两种类型的范围 .

    • Global scope :在中宣布的变量全局范围可以非常顺利地用于程序中的任何位置 . 例如:
    var carName = " BMW";
    
    // code here can use carName
    
    function myFunction() {
         // code here can use carName 
    }
    
    • Functional scope or Local scope :在此范围内声明的变量只能在其自己的函数中使用 . 例如:
    // code here can not use carName
    function myFunction() {
       var carName = "BMW";
       // code here can use carName
    }
    
  • 28

    Javascript使用范围链来为给定函数 Build 范围 . 通常有一个全局范围,每个定义的函数都有自己的嵌套范围 . 在另一个函数中定义的任何函数都有一个链接到外部函数的局部作用域 . 始终是源中定义范围的位置 .

    范围链中的元素基本上是一个带有指向其父范围的指针的Map .

    解析变量时,javascript从最里面的范围开始并向外搜索 .

  • 23

    我发现许多刚接触JavaScript的人很难理解语言中默认情况下继承是可用的,并且到目前为止,函数范围是唯一的范围 . 我为去年年底写的一个名为JSPretty的美化家提供了扩展 . 功能颜色代码中的函数范围,并始终将颜色与该范围中声明的所有变量相关联 . 当在不同范围内使用具有来自一个范围的颜色的变量时,可视地演示闭合 .

    尝试以下功能:

    观看演示:

    查看代码:

    目前,该功能支持深度为16的嵌套函数,但目前不对全局变量着色 .

  • 224

    JavaScript只有两种类型的范围:

    • Global Scope :全局只是一个窗口级别的范围 . 这里,整个应用程序中都存在变量 .

    • Functional Scope :在具有 var 关键字的函数内声明的变量具有功能范围 .

    无论何时调用函数,都会创建一个变量范围对象(并包含在范围链中),后面跟着JavaScript中的变量 .

    a = "global";
             function outer(){ 
                  b = "local";
                  console.log(a+b); //"globallocal"
             }
    outer();
    

    范围链 - >

    • 窗口级别 - aouter 函数位于范围链的顶层 .

    • 当外部函数调用一个新的 variable scope object (并包含在作用域链中)中添加了变量 b .

    现在当一个变量 a 需要它时,它首先搜索最近的变量范围,如果变量不存在,那么它将移动到变量范围链的下一个对象 . 在这种情况下,它是窗口级别 .

  • 3

    全球声明的变量具有全局范围 . 在函数内声明的变量作用于该函数,并且阴影全局变量具有相同名称 .

    (我确信真正的JavaScript程序员可以在其他答案中指出很多细微之处 . 特别是我遇到了this page关于 this 究竟在什么时候的意思 . 希望this more introductory link足以让你开始 . )

  • 7

    ES5及更早版本:

    Javascript中的变量最初(pre ES6 )词法函数作用域 . 术语词法范围意味着您可以在代码中通过'looking'查看变量的范围 .

    使用 var 关键字声明的每个变量都作用于该函数 . 但是,如果在该函数内声明了其他函数,那么这些函数将可以访问外部函数的变量 . 这称为 scope chain . 它的工作方式如下:

    • 当函数查找解析变量值时,它首先查看自己的范围 . 这是函数体,即大括号{}之间的所有内容(除了 other functions 中的变量,在此范围内) .

    • 如果找不到函数体内的变量 will climb up to the chain 并查看 where the function was defined 函数中的变量作用域 . 这就是词法范围的含义,我们可以在代码中看到定义了这个函数,因此可以通过查看代码来确定范围链 .

    示例:

    // global scope
    var foo = 'global';
    var bar = 'global';
    var foobar = 'global';
    
    function outerFunc () {
     // outerFunc scope
     var foo = 'outerFunc';
     var foobar = 'outerFunc';
     innerFunc();
     
     function innerFunc(){
     // innerFunc scope
      var foo = 'innerFunc';
      console.log(foo);
      console.log(bar);
      console.log(foobar);
      }
    }
    
    outerFunc();
    

    当我们尝试将变量 foobarfoobar 记录到控制台时会发生以下情况:

    • 我们尝试将foo记录到控制台,foo可以在函数 innerFunc 本身找到 . 因此,foo的值被解析为字符串 innerFunc .

    • 我们尝试将栏记录到控制台,在函数 innerFunc 本身内找不到栏 . 因此,我们需要 climb the scope chain . 我们首先查看定义函数 innerFunc 的外部函数 . 这是函数 outerFunc . 在 outerFunc 的范围内,我们可以找到变量bar,它包含字符串'outerFunc' .
      在innerFunc中找不到

    • foobar . . 因此,我们需要 climb the scope chain 到innerFunc范围 . 它也在这里找不到,我们爬到另一个级别 global scope (即最外面的范围) . 我们在这里找到变量foobar,其中包含字符串'global' . 如果在攀爬范围链后它没有找到变量,那么JS引擎会抛出 referenceError .

    ES6(ES 2015)及更早:

    词法范围和scopechain的相同概念仍然适用于 ES6 . 然而,引入了一种声明变量的新方法 . 有以下:

    • let :创建一个块范围变量

    • const :创建一个块范围的变量,该变量必须初始化且无法重新分配

    varlet / const 之间的最大区别在于 var 是函数作用域而 let / const 是块作用域 . 这是一个例子来说明这一点:

    let letVar = 'global';
    var varVar = 'global';
    
    function foo () {
      
      if (true) {
        // this variable declared with let is scoped to the if block, block scoped
        let letVar = 5;
        // this variable declared with let is scoped to the function block, function scoped
        var varVar = 10;
      }
      
      console.log(letVar);
      console.log(varVar);
    }
    
    
    foo();
    

    在上面的示例中,letVar将值记录为全局值,因为使用 let 声明的变量是块作用域 . 它们不再存在于各自的块之外,因此无法在if块之外访问该变量 .

  • 2321

    1)有一个全局范围,一个函数范围,以及with和catch范围 . 对于变量,通常没有“块”级别范围--with和catch语句为其块添加名称 .

    2)范围由函数嵌套到全局范围 .

    3)通过原型链解决属性问题 . with语句将对象属性名称带入with块定义的词法范围 .

    编辑:ECMAAScript 6(Harmony)规格支持let,我知道chrome允许'和谐'标志,所以也许它确实支持它..

    我们将支持块级别范围,但您必须使用该关键字来实现它 .

    编辑:基于本杰明's pointing out of the with and catch statements in the comments, I' ve编辑的帖子,并添加了更多 . with和catch语句都将变量引入各自的块,这是一个块范围 . 这些变量别名为传递给它们的对象的属性 .

    //chrome (v8)
    
     var a = { 'test1':'test1val' }
     test1   // error not defined
     with (a) { var test1 = 'replaced' }
     test1   // undefined
     a       // a.test1 = 'replaced'
    

    编辑:澄清示例:

    test1的作用域为with块,但是别名为a.test1 . 'var test1'在上部词汇上下文(函数或全局)中创建一个新的变量test1,除非它是a的属性 - 它是什么 .

    哎呀!小心使用'with' - 如果变量已在函数中定义,就像var是noop一样,对于从对象导入的名称,它也是一个noop!对已经定义的名称提出一点看法会使这更加安全 . 我个人永远不会因此而使用 .

  • 5

    全球范围:

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

    //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
    

    Check this article for in-depth understanding of scope

  • -2

    我认为我能做的最好的事情就是给你一些学习的例子 . Javascript程序员实际上根据他们理解范围的程度进行排名 . 它有时可能非常违反直觉 .

    • A globally-scoped variable
    // global scope
    var a = 1;
    
    function one() {
      alert(a); // alerts '1'
    }
    
    • Local scope
    // global scope
    var a = 1;
    
    function two(a) { // passing (a) makes it local scope
      alert(a); // alerts the given argument, not the global value of '1'
    }
    
    // local scope again
    function three() {
      var a = 3;
      alert(a); // alerts '3'
    }
    
    • Intermediate :没有JavaScript中的块作用域(ES5; ES6引入let

    一个 .

    var a = 1;
    
    function four() {
      if (true) {
        var a = 4;
      }
    
      alert(a); // alerts '4', not the global value of '1'
    }
    

    var a = 1;
    
    function one() {
      if (true) {
        let a = 4;
      }
    
      alert(a); // alerts '1' because the 'let' keyword uses block scoping
    }
    
    • Intermediate :对象属性
    var a = 1;
    
    function Five() {
      this.a = 5;
    }
    
    alert(new Five().a); // alerts '5'
    
    • Advanced :关闭
    var a = 1;
    
    var six = (function() {
      var a = 6;
    
      return function() {
        // JavaScript "closure" means I have access to 'a' in here,
        // because it is defined in the function in which I was defined.
        alert(a); // alerts '6'
      };
    })();
    
    • Advanced :基于原型的范围解析
    var a = 1;
    
    function seven() {
      this.a = 7;
    }
    
    // [object].prototype.property loses to
    // [object].property in the lookup chain. For example...
    
    // Won't get reached, because 'a' is set in the constructor above.
    seven.prototype.a = -1;
    
    // Will get reached, even though 'b' is NOT set in the constructor.
    seven.prototype.b = 8;
    
    alert(new seven().a); // alerts '7'
    alert(new seven().b); // alerts '8'
    

    • Global+Local :一个额外复杂的案例
    var x = 5;
    
    (function () {
        console.log(x);
        var x = 10;
        console.log(x); 
    })();
    

    这将打印 undefined10 而不是 510 ,因为JavaScript总是将变量声明(而不是初始化)移动到作用域的顶部,使代码等效于:

    var x = 5;
    
    (function () {
        var x;
        console.log(x);
        x = 10;
        console.log(x); 
    })();
    
    • Catch clause-scoped variable
    var e = 5;
    console.log(e);
    try {
        throw 6;
    } catch (e) {
        console.log(e);
    }
    console.log(e);
    

    这将打印 565 . catch子句 e 内部影响全局变量和局部变量 . 但是这个特殊范围仅适用于捕获的变量 . 如果在catch子句中写入 var f; ,那么它与在try-catch块之前或之后定义它的方式完全相同 .

  • 4

    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);
    
  • 97

    ECMAScript 6引入了let和const关键字 . 可以使用这些关键字代替var关键字 . 与var关键字相反,let和const关键字支持在块语句中声明局部作用域 .

    var x = 10
    let y = 10
    const z = 10
    {
      x = 20
      let y = 20
      const z = 20
      {
        x = 30
        // x is in the global scope because of the 'var' keyword
        let y = 30
        // y is in the local scope because of the 'let' keyword
        const z = 30
        // z is in the local scope because of the 'const' keyword
        console.log(x) // 30
        console.log(y) // 30
        console.log(z) // 30
      }
      console.log(x) // 30
      console.log(y) // 20
      console.log(z) // 20
    }
    
    console.log(x) // 30
    console.log(y) // 10
    console.log(z) // 10
    
  • -3

    试试这个好奇的例子 . 在下面的例子中,如果a是一个初始化为0的数字,你会看到0然后是1.除了a是一个对象,javascript将传递f1的指针而不是它的副本 . 结果是您两次都获得相同的警报 .

    var a = new Date();
    function f1(b)
    {
        b.setDate(b.getDate()+1);
        alert(b.getDate());
    }
    f1(a);
    alert(a.getDate());
    
  • 35

    根据我的理解,关键是Javascript具有功能级别范围与更常见的C块范围 .

    Here is a good article on the subject.

  • 8

    在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 
        }
    }
    
  • 1

    全局:在函数外声明的变量

    Local:在函数内声明的变量,只能在该范围内调用

  • 0

    这是一个例子:

    <script>
    
    var globalVariable = 7; //==window.globalVariable
    
    function aGlobal( param ) { //==window.aGlobal(); 
                                //param is only accessible in this function
      var scopedToFunction = {
        //can't be accessed outside of this function
    
        nested : 3 //accessible by: scopedToFunction.nested
      };
    
      anotherGlobal = {
        //global because there's no `var`
      }; 
    
    }
    
    </script>
    

    您需要调查闭包,以及如何使用它们来制作private members .

  • 3

    在"Javascript 1.7"(Mozilla对Javascript的扩展)中,还可以使用let statement声明块范围变量:

    var a = 4;
     let (a = 3) {
       alert(a); // 3
     }
     alert(a);   // 4
    
  • 2

    运行代码 . 希望这会给出一个关于范围界定的想法

    Name = 'global data';
    document.Name = 'current document data';
    (function(window,document){
    var Name = 'local data';
    var myObj = {
        Name: 'object data',
        f: function(){
            alert(this.Name);
        }
    };
    
    myObj.newFun = function(){
        alert(this.Name);
    }
    
    function testFun(){
        alert("Window Scope : " + window.Name + 
              "\nLocal Scope : " + Name + 
              "\nObject Scope : " + this.Name + 
              "\nCurrent document Scope : " + document.Name
             );
    }
    
    
    testFun.call(myObj);
    })(window,document);
    

相关问题