搞懂变量声明提升

·变量声明提升

--let const

function aa() {
    console.log(x)   
    let x = '2';
};
aa();
初始化之前无法使用变量

此时,可以证明let 是没有变量提升的吗?NO NO NO ~

来看下一个例子

function aa() {
    console.log(x) 
    var x= '1'  
    let x = '2';
};
aa();
此时控制台报错,X已经被声明过了,此时可以证明,let是存在变量声明提升的。

·关于 function的声明,先声明的会被覆盖

function test() {
    a();
    function a() {
        console.log('1')
    }
    function a() {
        console.log('2')
    }
 }
 test();
//2

对于同名的函数声明和变量声明,采用的是忽略原则,由于在提升时函数声明会提升到变量声明之前,变量声明一定会被忽略,所以结果是函数声明有效

function test1() {
    console.log(typeof a);>>function  //声明阶段:函数式声明忽略字面量声明
    var a = '111';
    function a() {
        console.log(11)
    }
  console.log(typeof a);>>string //调用阶段:函数式声明提升,随后被字面量声明复盖
}
test1();  




//先声明函数后声明变量,证明上边的例子不是function覆盖了变量
function test2() {
    console.log(typeof a);
    function a() {
        
    }
    var a = '111';
}
test2()


// funct

·函数声明优先于函数表达式

var getName = function() {
  console.log(1)
}
function getName() {
  console.log(2)
}
getName()
//1
优先声明函数,然后再被函数表达式覆盖

 

·函数声明声明,立即可用

console.log(getName())
function getName() {
  console.log(2)
}
//>>2


函数表达式不可用
console.log(getName())
var getName=function(){
  console.log(2)
}
//>>getName is not a function

·同名声明,函数式声明VS字面量声明变量 ---函数VS变量

   console.log(getname)//>>>function 声明阶段: 函数声明会忽略字面量声明的变量
        var getname='john'
        function getname(){
            console.log('mary')
        }


console.log(getname())>>>john  //调用阶段:函数声明优先,随后被字面量声明复盖

·同名声明,函数式声明函数VS函数表达式 ---函数VS函数

     console.log(getname())>>>mary //声明阶段:函数声明会忽略函数表达式
        var getname=function(){
            console.log('john')
        }
        function getname(){
            console.log('mary')
        }
 console.log(getname())>>john  //调用阶段:函数式声明优先,随后被函数表达式

·变量VS函数VS函数表达式    >>声明阶段函数会忽略其他   >>调用阶段函数表达式才会赋值和覆盖

test();>>//’函数‘---函数可以直接调用,而调用阶段,同名函数会忽略其他声明
console.log(test); //  function test(){console.log("函数"); }声明阶段, 同名函数会忽略其他声明
function test() {
    console.log("函数");  
}
console.log(test);  //  function test(){console.log("函数"); } //声明阶段,同名函数会忽略其他声明
var test = "变量";
console.log(test);  //"变量"  此时test已经被赋值
var test = function(params) {
    console.log("函数表达式");
};
console.log(test);    //"函数表达式",此时test已经被函数表达式覆盖
test();               //调用阶段,函数表达式以执行顺序排到最后,覆盖之前的所有
 

 

//写在最后,可以得出  创建变量和函数表达式的方式,只要执行顺序在上面的,都可以看作是申明阶段,采取函数忽略变量原则,而在变量之后的,按执行顺序执行

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章