window and this keyword in JavaScript
The window keyword in JavaScript is used to refer to the global object in the browser. It is used to access the properties and methods of the global object, such as alert(), setTimeout(), document, etc.
It basically has access to everything that's in the global scope.
Global space: Anything that's not inside a function is in the global scope.
The this keyword in JavaScript refers to the object that is currently executing the code.
Whenever a JavaScript program is run, a Global Execution Context, global object(window for browser) is created.
Whenever an execution context is created, a this is created along with it.
We know that an execution context is created at global level as well as whenever a function call is incurred. So everytime a this will be created along with the execution context.
In the global space, this points to the window object.
#Global Level
this === window;
Output
true
Whatever function or variable we create in the global space, they get attached to the global object (window for browser).
var a = 10;
function b() {
var c = 20;
}
console.log(window.a);
console.log(a);
console.log(this.a);
console.log(c);
Output
10
10
10
Uncaught ReferenceError: c is not defined at <anonymous>
Let us now understand the above code.
In the global space, window object being the global object has access to everything declared in the global space. Hence the first line of output.
In the global space, if we can access the variables and functions directly without using the window keyword. Hence the second line of output.
In the global space this points to the window object and hence the third line of output.
In the fourth line of output, we see an error. This is because we're trying to access a variable directly which is not present in the global scope.
Notice anonymous in the error, it is nothing but the Global Execution Context.