JavaScript 008: this

Neha
GigaGuardian
Published in
2 min readDec 15, 2022
ImageSource

In a class definition in JavaScript, the `this` keyword refers to the current instance of the class. It is used to access the properties and methods of the class, and to provide a context for those properties and methods when they are called.

For example, consider the following class definition:

class Car {
constructor(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
}

getDetails() {
return this.year + ' ' + this.make + ' ' + this.model;
}
}

In this example, the `this` keyword is used in the `constructor` method to set the initial values for the `make`, `model`, and `year` properties of the `Car` instance. It is also used in the `getDetails` method to refer to those properties when returning the details of the car.

When we create a new `Car` instance and call the `getDetails` method, the `this` keyword will refer to the specific `Car` instance that we created, allowing us to access its properties and methods.

Here is an example of how we would use the `Car` class to create a new `Car` instance and call the `getDetails` method:

var car = new Car('Toyota', 'Camry', 2020);
console.log(car.getDetails()); // Output: 2020 Toyota Camry

In this example, when the `getDetails` method is called on the `car` object, the `this` keyword refers to the `car` object itself, and the `make`, `model`, and `year` properties are accessed using `this.make`, `this.model`, and `this.year`.

I hope you enjoyed this introduction to “this” keyword!

Follow me: LinkedIn, Twitter

--

--