这不是一个优先于另一个的问题(存在优先级,但这在很大程度上只是语义问题)。
这里重要的是变量声明的赋值部分是not提升,而整个函数定义is.
函数在变量声明之前被提升,但最终效果是相同的。
提升后,您的函数将如下所示:
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;
}
the x = 10
发生在所有提升完成之后,因此这就是保留在中的值x
.
To respond to @thefourtheye's request (I think this is what s/he is asking for), if your original function looked like this:
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);
}