七度&光 2009-02-01 08:27 采纳率: 22.2%
浏览 637
已采纳

Javascript 中变量的范围是什么?

What is the scope of variables in javascript? Do they have the same scope inside as opposed to outside a function? Or does it even matter? Also, where are the variables stored if they are defined globally?

转载于:https://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript

  • 写回答

24条回答 默认 最新

  • ℡Wang Yan 2009-02-01 08:58
    关注

    I think about the best I can do is give you a bunch of examples to study. Javascript programmers are practically ranked by how well they understand scope. It can at times be quite counter-intuitive.

    1. A globally-scoped variable

      // global scope
      var a = 1;
      
      function one() {
        alert(a); // alerts '1'
      }
      
    2. 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'
      }
      
    3. Intermediate: No such thing as block scope in JavaScript (ES5; ES6 introduces let)

      a.

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

      b.

      var a = 1;
      
      function one() {
        if (true) {
          let a = 4;
        }
      
        alert(a); // alerts '1' because the 'let' keyword uses block scoping
      }
      
    4. Intermediate: Object properties

      var a = 1;
      
      function Five() {
        this.a = 5;
      }
      
      alert(new Five().a); // alerts '5'
      
    5. Advanced: Closure

      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'
        };
      })();
      
    6. Advanced: Prototype-based scope resolution

      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'
      

    7. Global+Local: An extra complex Case

      var x = 5;
      
      (function () {
          console.log(x);
          var x = 10;
          console.log(x); 
      })();
      

      This will print out undefined and 10 rather than 5 and 10 since JavaScript always moves variable declarations (not initializations) to the top of the scope, making the code equivalent to:

      var x = 5;
      
      (function () {
          var x;
          console.log(x);
          x = 10;
          console.log(x); 
      })();
      
    8. Catch clause-scoped variable

      var e = 5;
      console.log(e);
      try {
          throw 6;
      } catch (e) {
          console.log(e);
      }
      console.log(e);
      

      This will print out 5, 6, 5. Inside the catch clause e shadows global and local variables. But this special scope is only for the caught variable. If you write var f; inside the catch clause, then it's exactly the same as if you had defined it before or after the try-catch block.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(23条)

报告相同问题?

悬赏问题

  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)