标签云

微信群

扫码加入我们

WeChat QR Code


if you do alert(window.myname); then you will get values

2018年09月25日49分10秒

dholakiyaankit I've tried using window.myname still it is saying undefined...

2018年09月24日49分10秒

BharatSoni window.myname works in my browser.

2018年09月25日49分10秒

It should work bharat

2018年09月25日49分10秒

dholakiyaankit I've tried in fiddle.. didn't work

2018年09月24日49分10秒

that I've understood, so there is now way to access a global variable with same name as local variable.. ??

2018年09月25日49分10秒

You should be able to access it by doing window.myname. See here: stackoverflow.com/questions/15826751/… But global variables are not usually considered a good practice, and in most cases it'd be better to define a global object and access it through that. i.e. var me = { myname: "initial" } then call me.myname in the function.

2018年09月24日49分10秒

It is not correct to say that variables declaration are moved on top. For example if on line 10 it is written var myname = "initial", the result we see is not like var myname = "initial" on line 1, but actually we see the behavior as if var myname is on line 1 and on line 10 it is assigned value i.e. myname = "initial"

2018年09月24日49分10秒

sir, I am not just trying to change the value.. what you are doing is changing the value of global variable itself.. I want to understand the concept "WHY" it is happening...

2018年09月24日49分10秒

This fixes the problem of alerting undefined, but it eliminates any local variables as it's only using the global variable myname.

2018年09月25日49分10秒

It is not replace the global variable. What is happening is called "variable hoisting". That is, myname var myname; gets inserted at the top of the function. Always initialize your variables before you use them you can refer this stackoverflow.com/questions/11938961/…

2018年09月24日49分10秒