是的,当使用 var 声明变量时,它会被提升。如果使用 var 声明函数,函数定义也会被提升。当变量被提升时,它被赋值为 undefined。当函数被提升时,它的函数体被赋值为新的函数。
例如,以下代码会导致 foo 函数被重新赋值,这可能导致意想不到的结果:
function test() {
foo(); // "b"
var foo = function() {
console.log("c");
}
}
function foo() {
console.log("b");
}
test();
要避免这种问题,可以使用 const 或 let 声明变量和函数,因为它们不会被提升。例如:
function test() {
foo(); // 抛出 ReferenceError
const foo = function() {
console.log("c");
}
}
function foo() {
console.log("b");
}
test();