This keyword in Javascript
Md. Imran Hossain
Posted on January 6, 2022
This
means the object that is executing the current function.
There are two cases mainly using the this
keyword.
If a function is not part of any object, it will simply reference the global window object.
If a function is a part of an object, we call it as method. Inside a method
this
reference the object.
Let’s see the this
use cases:
-
This
by default references the window object. So, inside a normal function (not method in an object)this
references the global window object.
function greeting() {
console.log(this)
}
greeting()
- Now, let’s see what
this
references inside an object.
Unlike the first case, here this
references the object itself it is in. So using this
the properties and methods of an object can be accessed.
Now if we consider a constructor function, let’s see what the this method references.
function Greeting(fname) {
this.fname = fname
console.log(this)
}
const greetingObj = new Greeting('john')
Again, we see this referencing Greeting object (We call the constructor function using new keyword which creates an empty object, so this
keyword eventually references the empty object)
Now, Let’s see what will happen if we use this
keyword inside a function of a method.
const books = {
author: 'john doe',
books: ['history', 'english', 'math'],
findBooks() {
this.books.forEach(function (item) { console.log(this.author, item) })
}
}
books.findBooks()
output:
The output should print the author name instead of undefined. So what’s wrong here! The callback function inside foreach
is not a part of findbooks method, rather it’s a regular function which references the global window object
, that’s why this.author
yields to undefined.
To access the author property of book object, we use the second argument of forEach
method. The second argument provides the object value that is required for this.
const books = {
author: 'john doe',
books: ['history', 'english', 'math'],
findBooks() {
this.books.forEach(function (item) { console.log(this.author, item) }, this)
}
}
books.findBooks()
this
as the second argument is the reference of books object which is accessed from inside of the callback function. But all the Javascript methods don't provide this
(object) as argument.
In this case, we use some techniques like, 1. data binding 2. arrow function 3. Assigning this to another variable(closure concept). All the details is discussed in this article
Posted on January 6, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 25, 2024