问题描述
我刚读了一篇关于他给出了以下示例:
I just read a great article about JavaScript Scoping and Hoisting by Ben Cherry in which he gives the following example:
var a = 1;
function b() {
a = 10;
return;
function a() {}
}
b();
alert(a);
使用上面的代码,浏览器会提示1。
Using the code above, the browser will alert "1".
我仍然不确定为什么它会返回1。他说的一些事情就像:
所有函数声明都被提升到顶部。您可以使用函数来调整变量的范围。仍然没有为我点击。
I'm still unsure why it returns "1". Some of the things he says come to mind like: All the function declarations are hoisted to the top. You can scope a variable using function. Still doesn't click for me.
推荐答案
功能提升意味着功能被移动到其范围的顶部。也就是说,
Function hoisting means that functions are moved to the top of their scope. That is,
function b() {
a = 10;
return;
function a() {}
}
将由interpeter重写到这个
will be rewritten by the interpeter to this
function b() {
function a() {}
a = 10;
return;
}
很奇怪,是吗?
此外,在这个例子中,
function a() {}
表现与
var a = function () {};
所以,从本质上讲,这就是代码正在做:
So, in essence, this is what the code is doing:
var a = 1; //defines "a" in global scope
function b() {
var a = function () {}; //defines "a" in local scope
a = 10; //overwrites local variable "a"
return;
}
b();
alert(a); //alerts global variable "a"
这篇关于Javascript函数范围和提升的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!