Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

odd javascript remembrance in Chrome

I have the following in index.html:

<html><body><pre>
<script src="program.js"></script>
</pre></body></html>

And the following in program.js:

document.writeln(JSON.stringify(name));
name = "Bob";

Opening index.html for the first time, this is produced (output A):

> ""

Then, after refreshing the page, this is produced (output B):

> "Bob"

I do not ever see output B in Firefox.

Going back to Chrome: if, however, I use some variable other than 'name', such as 'val':

document.writeln(JSON.stringify(val));
val = "Bob";

I get an exception:

Uncaught ReferenceError: val is not defined 

So, since 'name' happens to be in the global scope, I thought that Chrome was somehow remembering global variables from old page loads, and setting default values of the those variables in new page loads. But, if I use the global variable 'status' instead, I always see output A.

Why is this happening?

like image 915
Robz Avatar asked Jan 10 '13 03:01

Robz


1 Answers

It looks like the name variable in the global context is some kind of reserved name in chrome. The same is applicable for variables like status as they can take only String values.

This name attribute refers to the name of the window object, which is persisted as long as the window is alive, so the value is shared between multiple documents.

Ex: var status = {}; alert(status) will alert [Object object] same with name also.

I don't have any reference doc to provide for this behaviour but something I noticed as a result in a bug report on one of my project.

like image 181
Arun P Johny Avatar answered Nov 15 '22 00:11

Arun P Johny