Nik*_*Pai 5 javascript function hoisting
在提升中,变量优先于函数定义还是反之亦然?请看下面的代码:
function a()
{
var x = 10;
function x() {
return 20;
}
return x;
}
Run Code Online (Sandbox Code Playgroud)
这不是一个优先于另一个的问题(存在优先权,但这在很大程度上只是语义问题)。
这里重要的是变量声明的赋值部分没有提升,而整个函数定义是。
函数在变量声明之前被提升,但最终效果是相同的。
提升后,您的函数将如下所示:
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;
}
Run Code Online (Sandbox Code Playgroud)
发生x = 10在所有提升完成之后,因此这就是 中保留的值x。
function a() {
function x() {
return 20;
}
var x = 10;
return x;
}
Run Code Online (Sandbox Code Playgroud)
那么吊装之后就变成这样了(同上):
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;
}
Run Code Online (Sandbox Code Playgroud)
最后一个例子,试试这个:
function a() {
console.log(x);
var x = 10;
console.log(x);
function x() { return 20; };
}
Run Code Online (Sandbox Code Playgroud)
调用时,会打印出:
function x() { return 20; }
10
Run Code Online (Sandbox Code Playgroud)
原因是提升导致函数的行为如下:
function a() {
var x = function x() { return 20; };
var x;
console.log(x);
x = 10;
console.log(x);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1550 次 |
| 最近记录: |