Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript variable scope in Google Chrome

I've got the following code :

<!DOCTYPE html>
<html>

<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Untitled 1</title>
</head>

<body>

<p id="p"></p>

<script>

var top = 9;
( function () {  top += 1;  document.getElementById( "p" ).innerHTML = top;  } )()

</script>

</body>

</html>

It works fine in Internet Explorer ( prints 10 ), but in Google Chrome it prints [object Window]. But if i change it like this:

( function () {  var top = 9; top += 1; document.getElementById( "p" ).innerHTML = top; } )()

it works in Chrome fine too. The only change is that the variable is now local. Does it mean that in Chrome i can't access global variables? Whatever i do i can't get the right result..

like image 697
Alex Oswald Avatar asked Aug 14 '26 01:08

Alex Oswald


1 Answers

Change your variable name, as it's conflicting with the Window.top global object. See the MDN doc page

like image 157
Sterling Archer Avatar answered Aug 15 '26 16:08

Sterling Archer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!