Javascript全局变量作用域问题 [英] Javascript global variable scope issue

查看:115
本文介绍了Javascript全局变量作用域问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个奇怪的范围问题(参见 JSFiddle ):

  var someGlobal = 3; 

函数someF(){$​​ b $ b //未定义的问题
alert(someGlobal);
var someGlobal = 5;
//显示5
alert(someGlobal);
}

函数someF2(){
//显示3,为什么?
alert(someGlobal);
}

someF();
someF2();

为什么JavaScript不会在 someF2() code>?如何 someF2()可以访问 someGlobal someF()不是?我怎样才能确保一个全局变量可以在函数中访问?

备注:

在这两种情况下,函数都是通过调用 alert(someglobal)开始的,为什么一个函数抛出一个未定义的问题,另一个不是?

$ b $创建一个名为 someGlobal 的新变量(局部范围的变量) code>(它掩盖全局 someGlobal )并为其分配一个值。它不会触及全局 someGlobal (尽管由于另一个变量名称相同,所以无法访问它)。



var 语句被挂起,所以 someGlobal 被所有 掩盖 someF (不只是在 var 语句之后)。本地 someGlobal 的值是 undefined ,直到赋值给它为止。



someF2 访问原始(未触及的)全局 someGlobal


I am running into a strange scope issue with Javascript (see JSFiddle):

var someGlobal = 3;

function someF() {
    // undefined issue
    alert(someGlobal);
    var someGlobal = 5;
    // Displays 5
    alert(someGlobal);
}

function someF2() {
    // Displays 3, why?
    alert(someGlobal);
}

someF();
someF2();

Why doesn't Javascript throws an undefined issue in someF2()? How come someF2() can access the someGlobal, and someF() not? How can I make sure a global variable is accessible in a function?

Remark:

In both cases, the functions start by calling alert(someglobal), why does one function throw an undefined issue and the other not?

解决方案

someF creates a new (locally scoped) variable called someGlobal (which masks the global someGlobal) and assigns a value to it. It doesn't touch the global someGlobal (although cannot access it because there is another variable with the same name in scope).

var statements are hoisted, so someGlobal is masked for all of someF (not just after the var statement). The value of the local someGlobal is undefined until a value is assigned to it.

someF2 access the original (untouched) global someGlobal.

这篇关于Javascript全局变量作用域问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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