这不是一个优先于另一个的问题(存在优先级,但这主要只是语义问题)。
这里重要的是变量声明的赋值部分没有提升,而整个函数定义是。
函数在变量声明之前被提升,但最终效果是一样的。
提升之后,你的函数会是这样的:
function a()
{
var x = function x() { // hoisted function declaration/definition
return 20;
};
var x; // hoisted variable declaration
x = 10; // unhoisted part of variable declaration
return x;
}
x = 10 发生在所有提升完成后,所以这是 x 中保留的值。
要响应@thefourtheye 的请求(我认为这是她/他所要求的),如果您的原始功能如下所示:
function a() {
function x() {
return 20;
}
var x = 10;
return x;
}
那么吊起来之后就是这个样子(同上):
function a() {
var x = function x() { // hoisted function declaration/definition
return 20;
}
var x; // hoisted variable declaration (does nothing)
x = 10; // unhoisted variable assignment
return x;
}
作为最后一个例子,试试这个:
function a() {
console.log(x);
var x = 10;
console.log(x);
function x() { return 20; };
}
调用时,会打印出来:
function x() { return 20; }
10
原因是提升导致函数的行为如下:
function a() {
var x = function x() { return 20; };
var x;
console.log(x);
x = 10;
console.log(x);
}