In javascript,every variable declaration is hoisted to the top of its declaration context.

原理:在运行时,所有的变量声明都会在函数执行前移动到函数的顶端,这种行为被称为变量提升。

上个栗子?

function test() { 
   console.log(hoisting);
   var hoisting = 'test'; 
};
test()  //undefined

/*实际执行顺序*/
function test() { 
   var hoisting;
   console.log(hoisting);  //undefined
   hoisting = 'test'; 
};

经常遇见的面试题

console.log(hoisting);
var hoisting = 100;
function test() { 
   console.log(hoisting);
   console.log(hoisting2);
   var hoisting = 200;
   var hoisting2 = 400;
   console.log(hoisting);
   console.log(hoisting2);
};
test();
console.log(hoisting);
// 输出: undefined,undefined,undefined,200,400,100

/*实际执行顺序*/
var hoisting;
console.log(hoisting);  //undefined
hoisting = 100;
function test() { 
   var hoisting;
   var hoisting2;
   console.log(hoisting);  //undefined
   console.log(hoisting2);  //undefined
   hoisting = 200;
   hoisting2 = 400;
   console.log(hoisting);  //200
   console.log(hoisting2);  //400
};
console.log(hoisting);  //100
小总结

在变量的作用域内,不管变量在何处声明,都会被提升到作用域的顶部,但是变量初始化的顺序不变。


婉婉
294 声望14 粉丝

爱吃肉肉的小姐姐~