zoukankan      html  css  js  c++  java
  • js预解析

    上面这段代码中,函数声明在函数调用下,为什么会调用成功呢?

    hello();
    
    function hello(){alert("hello");}

    因为js在编译阶段预解析,将上面这段代码转换成:

    var hello = function(){alert('hello');};
    
    hello();

    只有函数声明才会被提升,函数表达式在预解析阶段不会被提升。

    再看一个案例:

    var a=1;
    
    function hello(){
    
        console.info(a);
    
        var a=2;
    
    }

    执行结果为什么是undefined呢?

    因为在预解析阶段,代码被转换成下面:

    var a=1;
    
    function hello(){
    
        var a;
    
        console.info(a);
    
        a=2;
    
    }

    所以执行结果是undefined

    这就是为什么js函数中变量声明建议写在最前面:

    function hello(){
    
      var a=1,b=2;
    
      console.info(a);
    
    }
  • 相关阅读:
    继承性03
    继承性
    Arrays与Math类
    Static关键字
    random模块,time模块,os模块,sys模块
    re模块
    冒泡排序、递归、二分查找
    内置函数
    生成器和生成器表达式
    迭代器
  • 原文地址:https://www.cnblogs.com/fanfan-90/p/11921803.html
Copyright © 2011-2022 走看看