Amauri
Amauri

Reputation: 550

Difference of Global and Window objects

What is the difference between the JavaScript Global object and Window object. I know in both, you don't have to declare the object to use the methods.

Upvotes: 1

Views: 115

Answers (3)

Scampbell
Scampbell

Reputation: 1575

In JavaScript that is running in a browser, window is at the top of the scope chain. If you define a "global" variable, it is implied that it is under the window object.

For example:

// Global variable
var g = 0;

function foo(){
    window.g = 1

    // This will output '1'
    alert(g); 
}

Upvotes: 0

leemeichin
leemeichin

Reputation: 3379

The window object encapsulates the global scope. Omitting var (or let) when declaring a variable will implicitly add that as a property to the global scope. It's unique in that sense since there is no equivalent to window when inside a different scope.

I'm going to quote myself on this one:

MDN's description of var states that the global scope is bound to the global object. This would suggest that declaring a variable (either with var at the top level, or without var inside a function) simply adds a new property to window (or an equivalent outside of the browser).

Try it out. Create a variable without using var, then look at the window object in your console. You'll see it in there. It's the equivalent of doing this:

Object.defineProperty(window, 'foo', {
 value: "bar",
 enumerable: true // see @dandavis' comment on iterating over implicit global vars
)}

This doesn't explain why that's the case. Just that window is unique in that everything is defined within it.

Upvotes: 1

Hans
Hans

Reputation: 2800

I could be wrong, but it seems to me that the so-called globals are defined under the window object.

Upvotes: 0

Related Questions