JavaScript global object

Execution Context(Global)

How do you get access to the window object and this variable ?
javascript object runs inside an execution context. The code what you write that wraps up inside that execution context along with other contexts during runtime.
The base execution context is one of those many execution contexts known as global execution context.
Global execution context available every where and all the places. And global execution context creates two things for you (you dont have to create) global object and 'this' variable.

So global object and 'this' created by javascript engine for you as a part of global execution context.
Lets test it !
Open any folder and create a file index.html and another file test.js' both should be empty. Write down the following code inside the html file.

		<script src="test.js"></script>

Now open index.html in google chrome and go to console(f12->developer tool->console) The document should open empty as there are nothing. Lets take a peek at the execution context by typing 'this' and hit enter. the 'this' object which is part of global execution context will be shown; in this case it is windows object.

				Cinque Terre

This execution context created by javascript engine and decided which object 'this' would point to; and this case its 'window' object. There is always a global object for javascript in case of browser its 'window' for other case it could be different. You also can type 'window' in the console and get the global object.

For now just consider code or variable that aren't inside a function are global. Don't think too much as of now ! We will cover more on this.
Lets go to our test.js file and write the bellow code and save the file. var a = 'hello world!'; function abc(){ }

Now reload index.html file in chrome. Go to js console (f12->developer tool->console).

				Cinque Terre

In javascript if variable and function are not inside a function those variable/functions gets attached with the global object. In this can we can variable 'a' and function 'abc' got attached with browser global object window.
We can type window.a and to see them attached with window object.
So variable and function when lexically not sitting inside a function they are right there sitting inside global object.

				Cinque Terre

Back Next