DEV Community

ihsaan muhammed
ihsaan muhammed

Posted on

USES OF "this" in JS

The "this" keyword in JavaScript refers to the object that is currently executing the code.
Its value depends on how a function is called.

1) "this" inside an object

this refers to the current object.
EXAMPLE:

let student = {
    name: "Ihsaan",
    age: 21,

    display: function() {
        console.log(this.name);
        console.log(this.age);
    }
};

student.display();
Enter fullscreen mode Exit fullscreen mode

OUTPUT:

Ihsaan
21

Enter fullscreen mode Exit fullscreen mode

2)"this" in a method

It is commonly used to access the properties and methods of an object.
EXAMPLE:

let car = {
    brand: "Toyota",
    showBrand: function() {
        console.log(this.brand);
    }
};

car.showBrand();


Enter fullscreen mode Exit fullscreen mode

OUTPUT:

Toyota
Enter fullscreen mode Exit fullscreen mode

3)"this" in a constructor function

When used with a constructor function, this refers to the new object being created.
EXAMPLE:

function Student(name, age) {
    this.name = name;
    this.age = age;
}

let s1 = new Student("Ihsaan", 21);

console.log(s1.name);
console.log(s1.age);

Enter fullscreen mode Exit fullscreen mode

OUTPUT:

Ihsaan
21

Enter fullscreen mode Exit fullscreen mode

4)"this" in a class

this is used to access the properties and methods of the current class object.
EXAMPLE:

class Student {
    constructor(name) {
        this.name = name;
    }

    display() {
        console.log(this.name);
    }
}

let s1 = new Student("Ihsaan");
s1.display();
Enter fullscreen mode Exit fullscreen mode

OUTPUT:

Ihsaan
Enter fullscreen mode Exit fullscreen mode

5) "this" in arrow functions

Arrow functions do not have their own this. They inherit this from the surrounding scope.
EXAMPLE:

let student = {
    name: "Ihsaan",

    display: function() {
        let show = () => {
            console.log(this.name);
        };

        show();
    }
};

student.display();

Enter fullscreen mode Exit fullscreen mode

OUTPUT:

Ihsaan
Enter fullscreen mode Exit fullscreen mode

Top comments (0)