CoursesGalaxy Courses Subscription Knowledge Hub
Knowledge Hub
Design Patterns


this 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 other languages.

Let's see some examples-

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)




Output

Window


(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.





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)




Output

obj


(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)




Output

obj
Inside display1
Window


(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.





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 is from his course on Advanced JavaScript.







Yearly Subscription


Advanced JavaScript


Design Patterns Through JavaScript

Explore

Courses

Subscription

Knowledge Hub

Design Patterns

Tech Articles

About Us

Overview

Contact Us

CourseGalaxy

CourseGalaxy is focused on transformation of Engineering graduate to Software Engineer to fill the gap between education and industry and provide the training on specific problems of industry to enhance the skills of Engineers in industry to do their job appropriately.

Learn From Us

2018 CourseGalaxy