> Articles > this keyword In JavaScript

this keyword In JavaScript

this keyword in JavaScript is very useful and used heavily. In this article we will explain this keyword in JavaScript.

What is this keyword in javascript?

When the function is invoked it will have this. The value of this depends on how function is called. It can not be set by assigning any value like in other languages.

Let's see some examples of this keyword in JavaScript-

Example 1

Context is global then this will point to Window object.

(1)

console.log(this);

Output

Window

(2)

var x = 10;

console.log(this);
console.log(this.x);

Output

Window
10

Example 2

this is inside the function and function is called then this will point to Window object.

(1)

this keyword In JavaScript - Source Code Example 2 - 1

Output

Window

(2)

this keyword In JavaScript - Source Code Example 2 - 2

Output

Window
10

Example 3

this is inside function and function is assigned to variable. If the function is called using variable then this will point to Window object.

this keyword In JavaScript - Source Code Example 3

Output

Window

Example 4

this is inside function and function is inside object literal. If the function is invoked using object then this will point to object.

(1)

this keyword In JavaScript - Source Code Example 4 - 1

Output

obj

(2)

this keyword In JavaScript - Source Code Example 4 - 2

Output

obj
5

Example 5

this is inside function and function is inside object literal. If the function is invoked using object then this will point to object. But inside object if function is assigned to variable and called using that variable then it will point to Window object.

(1)

this keyword In JavaScript - Source Code Example 5 - 1

Output

obj
Inside display1
Window

(2)

this keyword In JavaScript - Source Code Example 5 - 2

Output

obj
5
Inside display1
Window
10

Example 6

Problem of this inside function of object literal pointing to Window object can be addressed by having one self variable. The value of this can be assigned to self variable at the start of function and then self can be used further instead of this.

this keyword In JavaScript - Source Code Example 6

Output

obj
5
Inside display1
obj
5


Suresh Kumar Srivastava is founder of online learning site coursegalaxy.com and author of popular books C In Depth, Data Structures Through C In Depth. He has 18+ years experience in industry and worked on architecture and design of multiple products. This article this keyword In JavaScript is from his Advanced JavaScript course.