Javascript local and global variable confusion [duplicate]

匿名 (未验证) 提交于 2019-12-03 02:43:01

问题:

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):

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.

回答1:

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

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:

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 myname = "initial";  function c() {     alert(myname);     myname = "changed";     alert(myname); }  c();


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!