Does javascript implement lexical scoping?

This question already has an answer here:

  • What is the scope of variables in JavaScript? 25 answers
  • What's the difference between using “let” and “var” to declare a variable in JavaScript? 24 answers

  • In javascript there is only function level scope and global scope. you cannot create a block scope and it adds no special meaning and does not create any scope.

    And this is how your code ends up

    function foo()
    {
      var local = 1;
      local = 2;
      return local;
    }
    foo();
    

    In ES6 you can create block level scopes with the help of Let. ES6 is not supported yet. more on that here


    From the MDN :

    JavaScript does not have block statement scope; rather, a variable declared within a block is local to the function (or global scope) that the block resides within.

    The scope of a variable in JavaScript is the whole function in which it is declared (or the global scope), so you only have one variable local here.

    Your code is equivalent to

    function foo()
    {
      var local;
      local = 1;
      {
        local = 2;
      }
      return local;
    }
    foo()
    

    Note that ES6 (the new norm of JavaScript) does introduce a lexical scoping with let but it's not yet really available.

    链接地址: http://www.djcxy.com/p/40832.html

    上一篇: onload函数中的Javascript变量范围

    下一篇: JavaScript是否实现了词汇范围界定?