In a browser, the global scope refers to the window
object, which has a property called name
.
If you read about scoping in JavaScript, for example in W3Schools, you'll find this information (at the bottom of the page):
Your global variables (or functions) can overwrite window variables (or functions).
Any function, including the window object, can overwrite your global variables and functions.
That means that, if you try to define any variable or function which already exists as a member of the global window
object, you will not be able to do it. When you try to access them, you'll be accessing the global window
object member.
You can check that, after creating your object name === window.name
yields true, which means that it's not your object, but the window.name
property.
You can also check that whenever you create a var in the global scope, it's created as a member of window. i.e.
var x = 22;
window.hasOwnProperty('x'); // returns true
console.log(window.x); // you'll see 22 in your console
To get rid of this problem you need to scope your variable. JavaScript only creates new scopes in function's bodies. So, one way to create your own scope it's to use the "self executing anonymous function" pattern, which looks like this:
(function(){
/* new scope: variables are created here without window global object
* interference. You can still access globlas using window.globalName */
})();
You can read an interesting article on this pattern here.
In node.js there is no name
in the global scope, thus you don't have that problem. There is a great explanation of what is in node.js global scope in this great SO answer.