JavaScript'吊装' [英] JavaScript 'hoisting'

查看:110
本文介绍了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 (因为函数声明覆盖变量声明而不是变量初始化)所以我预计警报的值将是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!!

推荐答案


  1. 全局 a 设置为 1

  2. b()被称为

  3. function a(){} 已挂起并创建一个本地变量 a ,用于屏蔽全局 a

  4. 本地 a 设置为 10 (覆盖函数 a

  5. 全局 a (仍然 1 )已收到提醒

  1. The global a is set to 1
  2. b() is called
  3. function a() {} is hoisted and creates a local variable a that masks the global a
  4. The local a is set to 10 (overwriting the function a)
  5. The global a (still 1) is alerted

这篇关于JavaScript'吊装'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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