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函数作用域和提升
- 为什么悬停在委托事件处理程序中不起作用? 2022-01-01
- 我不能使用 json 使用 react 向我的 web api 发出 Post 请求 2022-01-01
- 从原点悬停时触发 translateY() 2022-01-01
- 使用 iframe URL 的 jQuery UI 对话框 2022-01-01
- 如何显示带有换行符的文本标签? 2022-01-01
- 如何调试 CSS/Javascript 悬停问题 2022-01-01
- 在不使用循环的情况下查找数字数组中的一项 2022-01-01
- 如何向 ipc 渲染器发送添加回调 2022-01-01
- 是否可以将标志传递给 Gulp 以使其以不同的方式 2022-01-01
- 为什么我的页面无法在 Github 上加载? 2022-01-01