Javascript - 悬挂优先 [英] Javascript - Precedence in hoisting
问题描述
在提升中,变量优先于函数定义还是相反?请参阅下面的代码:
In hoisting, do variables take precedence over function definition or the other way round? Please see the code below:
function a()
{
var x = 10;
function x() {
return 20;
}
return x;
}
推荐答案
这不是一个问题优先于另一个(有优先级发生,但这主要是一个语义问题)。
It's not a matter of one taking precedence over the other (there is precedence taking place, but that's largely just a matter of semantics).
重要的是变量声明的赋值部分是 not ,而整个函数定义是 >。
What matters here is that the assignment part of the variable declaration is not hoisted, whereas the entire function definition is.
注意根据raina77ow的回答,似乎我原来的部分假设是错误的。函数在变量声明前被挂起,但净效果是相同的。
Note Based on raina77ow's answer, it seems that part of my original assumptions were wrong. Functions are hoisted before variable declarations, but the net effect is the same.
提升后,您的函数将如下所示:
After hoisting, your function will act like this:
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
在完成所有提升后发生,因此这是
为了回应@ thefourtheye的请求(我认为这是他/她所要求的),如果您的原始函数如下所示:
the x = 10
takes place after all the hoisting is done, so that is the value that remains in 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;
}
然后在看起来像这样(与上面相同):
Then after hoisting, it would look like this (same as above):
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;
}
,试试这个:
As one last illustration, try this:
function a() {
console.log(x);
var x = 10;
console.log(x);
function x() { return 20; };
}
打印出来时:
When called, this prints out:
function x() { return 20; }
10
原因在于提升会导致函数的行为像这样:
The reason for this is that hoisting is causing the function to behave like this:
function a() {
var x = function x() { return 20; };
var x;
console.log(x);
x = 10;
console.log(x);
}
这篇关于Javascript - 悬挂优先的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!