提升意味着所有的声明都被移动到作用域的顶部。这发生在代码运行之前。
对于函数,这意味着你可以从作用域中的任何位置调用它们,甚至在它们被定义之前。
hello(); // Prints "Hello world! " even though the function is called "before" declaration
function hello(){
console.log("Hello world! ");
}
对于变量,提升有点不同。它在作用域的顶部将 undefined 分配给它们。
例如,在定义变量之前调用它:
console.log(dog);
var dog = "Spot";
结果是:
undefined
这可能令人惊讶,因为你可能预计它会导致错误。
如果你声明一个函数或变量,无论你在哪里声明它,它总是被移动到作用域的顶部。
提升意味着所有的声明都被移动到作用域的顶部。这发生在代码运行之前。
对于函数,这意味着你可以从作用域中的任何位置调用它们,甚至在它们被定义之前。
hello(); // Prints "Hello world! " even though the function is called "before" declaration
function hello(){
console.log("Hello world! ");
}
对于变量,提升有点不同。它在作用域的顶部将 undefined 分配给它们。
例如,在定义变量之前调用它:
console.log(dog);
var dog = "Spot";
结果是:
undefined
这可能令人惊讶,因为你可能预计它会导致错误。
如果你声明一个函数或变量,无论你在哪里声明它,它总是被移动到作用域的顶部。