当前位置: 移动技术网 > IT编程>开发语言>JavaScript > javascript:变量声明&&赋值的提升和函数声明&&定义的提升在不同情况下的表现

javascript:变量声明&&赋值的提升和函数声明&&定义的提升在不同情况下的表现

2019年09月19日  | 移动技术网IT编程  | 我要评论

console.log(a);             //undefined
console.log(show);             //函数的定义
show();                      //aaa123
var a = 1;
function show(){
  console.log("aaa123");
}
console.log(a);              //1
console.log(show);             //函数的定义
show();                      //aaa123


解释:这种情况下,变量声明得到提升(初始化赋值没有),函数的声明和定义也都得到提升



console.log(a);              //undefined
console.log(show);            //undefined
show();                      //报错
if(1)
{
  console.log(show);          //函数的第二种定义
  var a = 1;
  function show(){
    console.log("aaa123");
  }
  function show(){
    console.log("bbb456");
  }
}
console.log(a);              //1
console.log(show);            //函数的第二种定义
show();                      //bbb456


解释:这种情况下,变量声明得到提升(初始化赋值没有),函数的声明得到提升,但是并没有定义
因为函数的定义被放在了if语句中,js解释器猜测该函数可能有多个定义,但现在并不确定,需要等程序运行到那里才可以确定,
所以第一次输出show,结果为undefined,
而在进入if语句之后,因为函数声明和定义提升的缘故,马上可以确定,所以尽管第二次输出show在if语句块的开头,
但是依然可以正确的输出show函数的定义



console.log(a);                  //undefined
console.log(show);           //undefined
show();                        //报错
if(0)
{
  var a = 1;
  function show(){
    console.log("aaa123");
  }
  function show(){  
    console.log("bbb456");
  }
}
console.log(a);            //undefined
console.log(show);          //undefined
show();                    //报错


解释:因为判断条件为false,分支代码未执行,变量没有进行赋值操作,函数也没有定义

 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网