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

}

 

posted @ 2019-11-24 11:54  .Neterr  阅读(109)  评论(0编辑  收藏  举报