DEV Community

Md. Imran Hossain
Md. Imran Hossain

Posted on • Updated on

This keyword in Javascript

This means the object that is executing the current function.
There are two cases mainly using the thiskeyword.

  • 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 thisreference the object.

Let’s see the thisuse cases:

  1. Thisby default references the window object. So, inside a normal function (not method in an object) thisreferences the global window object.
function greeting() {
    console.log(this)
}
greeting()

Enter fullscreen mode Exit fullscreen mode

Image description

  1. Now, let’s see what thisreferences inside an object.

Image description
Image description

Unlike the first case, here thisreferences the object itself it is in. So using thisthe 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')
Enter fullscreen mode Exit fullscreen mode

Image description

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()
Enter fullscreen mode Exit fullscreen mode

output:

Image description

The output should print the author name instead of undefined. So what’s wrong here! The callback function inside foreachis 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()
Enter fullscreen mode Exit fullscreen mode

Image description
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

Top comments (0)