Introduction
One of the most confusing mechanism in Javascript is understanding the this keyword. It is a special identifier defined in the scope of every function, but what it refers to sometimes even may confuse even the seasoned JS developers.
Let's try to simplify and understand the this mechanism.
What is this?
In simple words:
thisis the object executing in the current function
Remember these simple thumb rules:
- If the executing function is a method an object then
thisrefers to that object itself (1) - Otherwise if it is a regular javascript function i.e. it is not a member function then
thisrefers to the global object which iswindowin browser andglobalin Node (2)
Let's try to understand the above thumb rules through series of examples
Example (1)
const song = {
title: "'song title',"
play() {
console.log(this)
}
}
song.stop = function() {
console.log(this)
}
song.play()
song.stop()
Output:
- We have a
songobject withplay()as method function. We have added anotherstop()function to the same object. - Since the
thisis inside method function it points to thesongobject.
Example (2)
function playSong() {
console.log(this)
}
playSong()
Output:
- We have a
playSong()function which doesn't links to any object. - In this case
thislinks to thewindowobject in browser.
Example 3
Let's Modify the above code to look something like:
function Song(title) {
this.title = title
console.log(this)
}
const songObj = new Song('song title')
Can you guess the output for above example?
Output
- We have a
Song()function which doesn't belong any object in the initially but later we create asongObj -
songObjis initialised using anewkeyword which creates an empty object and then pointsthisto the{}empty object. - Finally we add the
titleproperty tothisobject.
Example 4
Let's take a look at another example:
const song = {
title: 'song title',
comments: ['x', 'y', 'z'],
showComments () {
this.comments.forEach(function(comment){
console.log(this.title, comment)
})
}
}
song.showComments()
Output:
What is going on in the above example?
If you remove
titlefrom above example inconsole.log()you can see that thethisactually now points to the global (window) object.But we're inside the
songobject shouldn't thethispoint tosongobject?If you look at the function inside the
forEachloop it is just a regular javascript function, it is not a method inside thesongobject. Thesongobject only has one methodshowComments().So the
thisinside the anonymous callback function insideforEachloop holds context to the global object.
Now you must be wondering how can we solve this problem?
const song = {
title: 'song title',
comments: ['x', 'y', 'z'],
showComments () {
this.comments.forEach(function(comment){
console.log(this.title, comment)
}, this)
}
}
song.showComments()
- The second argument in the
forEachtakes the context info, so when we call theshowComments()while passingthisas the context we're still in the execution context ofshowComments(). - Now when you run the above code look at output.
Output:
Now every function in javascript doesn't accept the context argument, so how can we change the this context in javascript during runtime, will be covered in the next part (Part 2).
Thank You for Reading. Happy Learning!
References: Mosh Hamedani - JavaScript Fundamentals




Top comments (0)