Javascript function scoping and hoisting(Javascript函数作用域和提升)
问题描述
我刚刚阅读了 Ben Cherry 撰写的一篇关于 JavaScript 范围界定和提升的精彩文章 他举了以下例子:
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() {}
}
将被解释者重写为这个
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函数作用域和提升的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Javascript函数作用域和提升


基础教程推荐
- Bootstrap 模态出现在背景下 2022-01-01
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
- fetch 是否支持原生多文件上传? 2022-01-01
- 如何添加到目前为止的天数? 2022-01-01
- 检查 HTML5 拖放文件类型 2022-01-01
- Bokeh Div文本对齐 2022-01-01
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
- Fabric JS绘制具有活动形状的多边形 2022-01-01
- 在 contenteditable 中精确拖放 2022-01-01
- npm start 错误与 create-react-app 2022-01-01