JavaScript'吊装' [英] JavaScript 'hoisting'
本文介绍了JavaScript'吊装'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我遇到了JavaScript'hoisting'并且我没有弄清楚这段代码是如何运作的:
I came across JavaScript 'hoisting' and I didn't figure out how this snippet of code really functions:
var a = 1;
function b() {
a = 10;
return;
function a() {}
}
b();
alert(a);
我知道函数声明如( function a(){}
)将被提升到函数 b
范围的顶部,但它不应该覆盖 a $的值c $ c>(因为函数声明覆盖变量声明而不是变量初始化)所以我预计警报的值将是10而不是1 !!
I know that function declaration like ( function a() {}
) is going to be hoisted to the top of the function b
scope but it should not override the value of a
(because function declarations override variable declarations but not variable initialization) so I expected that the value of the alert would be 10 instead of 1!!
推荐答案
- 全局
a
设置为1
-
b()
被称为 -
function a(){}
已挂起并创建一个本地变量a
,用于屏蔽全局a
- 本地
a
设置为10
(覆盖函数a
) - 全局
a
(仍然1
)已收到提醒
- The global
a
is set to1
b()
is calledfunction a() {}
is hoisted and creates a local variablea
that masks the globala
- The local
a
is set to10
(overwriting the functiona
) - The global
a
(still1
) is alerted
这篇关于JavaScript'吊装'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文