Let's talk about 'this'

Let's talk about 'this'

'this' keyword is often the most confusing and mis-understood concept in JavaScript.

In this blog, I'll break down the different behaviours of this keyword given the different scenarios.

'this' in constructor functions

When invoking a constructor function with the new operator, this gets set to the newly created object.

function Person(name) {
    this.name = name;
     this.greetings = function () {
        console.log(`Welcome to the class of 2020, ${this.name}`);
     };
}
const student = new Person("John");
//Welcome to the class of 2020, John

In the above Person() construction function, the this.name refers to student object created. When this.name is encountered, it tries to access the name property of student object which is set to John.

'this' in methods

We sometimes would want to access the properties of an object in its methods, after all, methods are used to manipulate the values of its objects properties.

const person() = {
    name: "John",
    age: 20,

    greetings() {
       console.log(`Welcome to the class of 2020, ${this.name}`);
    };
}
person.greetings()
//Welcome to the class of 2020, John

In the above example, the value of 'this' is the object before dot which is person. So, to access the object the method can use 'this'.

'this' in functions

This is an interesting behaviour of 'this'. Try to guess what the value of 'this' when used inside a function.

 function greetings() {
     return this;
}
greetings();

Returning 'this' inside of greetings function looks like we are simply invoking the function itself and since every function in JavaScript is an Object and is created by Object constructor function which resides in the global context, the 'this' here would set to the global object window. Screenshot 2021-07-10 at 7.13.14 PM.png

All this while, we looked at the different behaviours of 'this' which was set automatically by the way we invoked the functions. But, what if we wanted to set the value of 'this' ourselves? Yes, that is possible and JavaScript provides us few methods to do just that.

I will cover that in the next blog. Watch out for it and give it a read!