为什么局部变量会杀死我的全局变量? [英] Why does local variable kill my global variable?

查看:156
本文介绍了为什么局部变量会杀死我的全局变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很抱歉,这个问题,但这个问题真的搞砸了我的一天。



以下代码警告 10 p>

  var globalId = '10'; 
函数check(){
alert(globalId);
}
check();

但是下一个代码提醒 undefined

  var globalId = '10'; 
函数check(){
alert(globalId);
var globalId;
}
check();

我知道如果我在一个函数中声明一个变量是一个局部变量,但如果我已经这是一个简单的例子,但在我原来的代码中,我做了一个简单的例子,但是在我的原始代码中,我没有定义 ?很多东西在函数的开始之间,然后很长一段时间我检查是否定义了 globalId ,否则定义它: if (!globalId){var globalId;} 这意味着位于函数顶部的警报生成未定义,就好像JavaScript首先执行整个函数一样,只是为了查看是否有可能的变量声明,如果是这样,声明它们,因此我的警报指向一个'未声明的'变量。

有人可以向我解释为什么会发生这种情况,如果这是真的在执行一个函数之前,JavaScript会预先声明所有的变量,即使是在条件中声明的变量甚至没有被符合?

解决方案

在JavaScript中,你应该知道有一种叫做 HOISTING 的东西。



这实际上意味着,当你声明任何局部变量时,变量声明自动带到作用域顶部。



例如: -

  var globalId = '10'; 
函数check(){
alert(globalId); var globalId; }
check();

更改为 -

  var globalId = '10'; 
函数check(){
var globalId;
alert(globalId);}
check();

由于globalID仍未分配任何值,因此它会在输出中返回undefined。局部变量总是优先于具有相同名称的全局变量。


Sorry for this question, but this issue really screwed up my day.

The following Code alerts 10 as it should:

var globalId='10';  
function check(){  
    alert(globalId);  
}  
check();

But this next code alerts undefined:

var globalId='10';  
function check(){  
    alert(globalId); 
    var globalId; 
}  
check();

I am aware that if I declare a variable in a function its a local variable, but if I already declared it as global, how can it be that my alerts says undefined?

This is an easy example, but in my original code I did a lot of stuff in between the beginning of the function, then a long way down I checked to see if globalId was defined, else define it: if(!globalId){var globalId;} This meant that my alert situated at the top of the function generated undefined, as if JavaScript first executed the whole function, just to see if any variables 'might' be declared, and if so, declare them and therefore my alert pointed to an 'undeclared' variable.

Can anybody explain to me why this happen, and if it is true that JavaScript "pre-declares" all variables before executing a function, even variables declared in conditions not even met?

解决方案

In javascript, you should know there is something called as HOISTING.

What this essentially means is, when you declare any local variables, the variable declaration is automatically carried to top of the scope.

eg:-

var globalId='10';
function check(){
alert(globalId); var globalId; }
check(); 

Changes to -

var globalId='10';
function check(){
var globalId;
alert(globalId);}
check(); 

Since globalID is still not assigned any value, it returns undefined in your output. The local variables always get priority over the global variables with same name.

这篇关于为什么局部变量会杀死我的全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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