zoukankan      html  css  js  c++  java
  • js作用域和变量提升

    Function declarations and variable declarations are always moved (“hoisted”) invisibly to the top of their containing scope by the JavaScript interpreter.

    example1 :

        var foo = 1;
        function bar() {
          if (!foo) {
            var foo = 10;
          }
          console.log(foo); // 10
        }
        bar();

    example2 : 

        var a = 1;
        function b() {
          a = 10;
          return;
          function a() { }
        }
        b();
        console.log(a); // 1

    example3 :

        var x = 1;
        console.log(x); // 1
        if (true) {
          var x = 2;
          console.log(x); // 2
        }
        console.log(x); // 2

    example4:

      function foo() {
          var x = 1;
          if (x) {
            (function () {
              var x = 2;
              // some other code
            } ());
          }
          // x is still 1.
        }

    Named Function Expressions

    You can give names to functions defined in function expressions, with syntax like a function declaration. This does not make it a function declaration, and the name is not brought into scope, nor is the body hoisted. Here’s some code to illustrate what I mean:

    example 5:

        foo(); // TypeError "foo is not a function"
        bar(); // valid
        baz(); // TypeError "baz is not a function"
        spam(); // ReferenceError "spam is not defined"
    
        var foo = function () { }; // anonymous function expression ('foo' gets hoisted)
        function bar() { }; // function declaration ('bar' and the function body get hoisted)
        var baz = function spam() { }; // named function expression (only 'baz' gets hoisted)
    
        foo(); // valid
        bar(); // valid
        baz(); // valid
        spam(); // ReferenceError "spam is not defined"

    example 6:

       getName(); //5
        var getName = function () { console.log(4); };
        function getName() { console.log(5); };
        getName();//4

    example 7:

        function Foo() {
          getName = function () { console.log(1); };
          return this;
        }
        Foo.getName = function () { console.log(2); };
        Foo.prototype.getName = function () { console.log(3); };
        var getName = function () { console.log(4); };
        function getName() { console.log(5); };
    
        Foo.getName(); //2 
        getName(); //4
        Foo().getName(); //1
        getName(); //1
        new Foo.getName(); //2
        new Foo().getName(); //3 
        new new Foo().getName(); //3
  • 相关阅读:
    windows编程:第一个windows程序
    百度地图API多个点聚合时,标注添加的标签label地图刷新就丢失的问题解决
    在WPF的WebBrowser控件中屏蔽脚本错误的提示
    使用SQL语句逐条更新每条记录
    通过 HDU 2048 来初步理解动态规划
    一个乱码问题
    2、设置配置文件
    1、搭建 maven 环境
    MyBatis 缓存机制
    关于 Mybatis 设置懒加载无效的问题
  • 原文地址:https://www.cnblogs.com/leonwang/p/5204441.html
Copyright © 2011-2022 走看看