函数表达式和函数声明的区别

// js中的作用域是以函数为边界的

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

function foo() {  
    var x = 1;  
    if (x) {  
        (function() {  
            var x = 2;  
        }());  
    }  
    console.log(x);  
}  
foo();// 1
1. 只有函数声明才会进行函数提升
2. 函数提升会将函数体一起提升上去,这点与变量提升有所不同

a();// 123  

var a = function(){  
    console.log("321");  
}  

a();// 321  

function a(){  
    console.log("123");  
}

===》等价于

var a = function a(){  
    console.log("123");  
}  

a();  

a = function(){  
    console.log("321");  
}  

a();
function fn(){  
    console.log(a);  
    var a = 2;  
    function a(){}  
    console.log(a);  
}  
fn();// function a(), 2  

函数提升比变量提升优先级高,因为函数提升是将函数体整体提升,提升上去后立马赋值

results for ""

    No results matching ""