javascript中的全局范围和本地范围 [英] global scope and local scope in javascript

查看:103
本文介绍了javascript中的全局范围和本地范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在javascript中考虑以下代码段。
以下代码段的输出为:
第一个警报显示未定义,而第二个警报显示2

Consider the following snippet in javascript. The output of the following snippet is : The first alert shows "undefined" whereas the second alert shows "2"

var a = 1;
function test(){
    alert(a);
    var a = 2;
    alert(a);
}
test();

为什么第一个警报不显示全局变量a的值为1?

Why does the first alert not show the value of the global variable a which is 1?

推荐答案

在JavaScript中称为吊装。您的函数会自动转换为以下函数:

It is called "hoisting" in JavaScript. Your function is automatically transformed into this one:

var a = 1;
function test() {
  var a;
  alert(a);
  a = 2;
  alert(a);
}
test();

很好读到: http://net.tutsplus.com/tutorials/javascript-ajax/quick-tip-javascript-hoisting-explained/

这篇关于javascript中的全局范围和本地范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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