Javascript函数作用域和提升 [英] Javascript function scoping and hoisting

查看:21
本文介绍了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函数作用域和提升的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆