3

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..

2
  • Don't use global variables. Commented Nov 7, 2014 at 21:17
  • window.top is an object Commented Nov 7, 2014 at 21:17

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

6 Comments

I had the same issue with a variable named status. Learned the hard way lol
These name conflicts seem really unconvinient. That's the big disadvatage of javascript and other such languages i think.. In Java language there are no such problems for example
Of course there are. Every try to assign a reserved word in Java?
That's just reserved words :) There are little bit of them and you can remember almost all of them since they're commonly used. But in other languages there are many such "hidden" words, which you don't know about. And it's just unconvinient to have one big global namespace
@AlexOswald and that's precisely why your second function works - it's because it is NOT in the global namespace. There are two namespaces - global and function, it's advisable to not use global for the precise reason you saw.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.