Artem
Artem

Reputation: 2500

Why can we access window.document property without specifying window object?

As a JavaScript newcomer I see a lot of magic which isn't explained in books. For example, why can I write

document.getElementById('one');

When document is a property of window? From what I've read in books, we need to write

window.document.getElementById('one');

If document would be regular object like any object we would create by ourselves.


What allows us to omit window parent object while working with document property?

I googled this, but I couldn't find an explanation.

Upvotes: 7

Views: 2202

Answers (2)

Mahipal
Mahipal

Reputation: 519

window represents the browser's window. All global JavaScript objects, functions, and variables automatically become members of the window object.

document is also a property of global object and hence can be accessed as window.document or document.

For more information, you can refer here.

Upvotes: 0

Scott Marcus
Scott Marcus

Reputation: 65806

window is the Global object in a browser and because of the way scope works in JavaScript, the Global object will always be the last place that is searched for something. So, omitting window is OK because it will wind up being found at the end of the "scope chain".

document is a property of window and, as such, you do not need to qualify it with window for it to be found because when the browser reaches window and still hasn't found what it's looking for, it will look at the properties of window and find document there.

Upvotes: 5

Related Questions