变量提升与函数提升
下面代码打印的结果是什么?
function hoistFunction() {
foo()
var foo = function () {
console.log(1)
}
foo()
function foo () {
console.log(2)
}
foo()
}
hoistFunction()
这段代码执行时候会进行变量函数提升,提升后的代码为,执行结果2 1 1
function hoistFunction() {
// 函数提升优先级最高
function foo() {
console.log(2)
}
// 变量定义提升
var foo
foo() // 2
// 赋值,由于这里foo与上面foo函数重名所以覆盖
foo = function() {
console.log(1)
}
foo() // 1
foo() // 1
}
hoistFunction()