开发者

Javascript global variable

开发者 https://www.devze.com 2023-01-07 13:15 出处:网络
I have a script tag with \'A\' variable and has been initialised as 16 but when I use alert on IE under onclick event, I received undefine rather than 16.

I have a script tag with 'A' variable and has been initialised as 16 but when I use alert on IE under onclick event, I received undefine rather than 16.

Is this the probl开发者_高级运维em in IE 6?

e.g.

<script type="text/javascript">
var A =16;
</script>

<a href=""  onclick="javascript:alert(A);">undefine</a>


I'd bet on it being caused by some slight confusion...

Being that putting var in front of a variable puts that variable into the local scope only in Javascript, and a variable delcaration without it (a = 16) is global.

function test() {
    a = 16;
    var b = 16;

}
test();

alert(a); # alerts 16
alert(b); # throws error, b is undefined


This is just a simple concept of global and local variable.. when You run the method the variable which is global has got its value and the variable which is local has also got the value but its lifecycle expires on going out of function thus it throws error to be undefined


You need to post an example of what you are talking about, but the problem may be in where your script tag is and where you are calling the variable from.

0

精彩评论

暂无评论...
验证码 换一张
取 消