Javascript本地和全局变量混淆[重复]

时间:2021-08-05 09:20:05

This question already has an answer here:

这个问题已经有了答案:

I am new to JavaScript and I was doing some practices on local and global variable scopes, following is my code(fiddle):

我是JavaScript新手,我在本地和全局变量作用域上做了一些实践,以下是我的代码(fiddle):

var myname = "initial"
function c(){
    alert(myname);
    var myname = "changed";
    alert(myname);
}
c();

when the first alert is called, it is showing myname as undefined. so my confusion is why I am not able to access a global instance of myname and if I don't define myname within the function then it will work fine.

当第一个警报被调用时,它将显示myname未定义。所以我的困惑是为什么我不能访问myname的全局实例,如果我不在函数中定义myname,那么它就可以正常工作。

2 个解决方案

#1


42  

In Javascript, the variable declarations are automatically moved to the top of the function. So, the interpreter would make it look more like this:

在Javascript中,变量声明会自动移动到函数的顶部。所以,解释器会让它看起来更像这样:

var myname = "initial"
function c(){
    var myname;
    // alerts undefined
    alert(myname);
    myname = "changed";
    // alerts changed
    alert(myname);
}
c();

This is called 'hoisting'.

这就是所谓的“提升”。

Due to hoisting and the fact that the scope for any variable is the function it's declared in, it's standard practice to list all variables at the top of a function to avoid this confusion.

由于提升和任何变量的作用域都是它声明的函数,所以在函数的顶部列出所有变量是标准的做法,以避免这种混淆。

#2


6  

It is not replace the global variable. What is happening is called "variable hoisting". That is, var myname; gets inserted at the top of the function. Always initialize your variables before you use them - try this:

它不是替换全局变量。所发生的一切被称为“变量提升”。也就是说,var的名字;在函数的顶部插入。在使用变量之前一定要初始化它们——试试这个:

var myname = "initial";

function c() {
    alert(myname);
    myname = "changed";
    alert(myname);
}

c();

#1


42  

In Javascript, the variable declarations are automatically moved to the top of the function. So, the interpreter would make it look more like this:

在Javascript中,变量声明会自动移动到函数的顶部。所以,解释器会让它看起来更像这样:

var myname = "initial"
function c(){
    var myname;
    // alerts undefined
    alert(myname);
    myname = "changed";
    // alerts changed
    alert(myname);
}
c();

This is called 'hoisting'.

这就是所谓的“提升”。

Due to hoisting and the fact that the scope for any variable is the function it's declared in, it's standard practice to list all variables at the top of a function to avoid this confusion.

由于提升和任何变量的作用域都是它声明的函数,所以在函数的顶部列出所有变量是标准的做法,以避免这种混淆。

#2


6  

It is not replace the global variable. What is happening is called "variable hoisting". That is, var myname; gets inserted at the top of the function. Always initialize your variables before you use them - try this:

它不是替换全局变量。所发生的一切被称为“变量提升”。也就是说,var的名字;在函数的顶部插入。在使用变量之前一定要初始化它们——试试这个:

var myname = "initial";

function c() {
    alert(myname);
    myname = "changed";
    alert(myname);
}

c();