Instance Methods in JavaScript Classes (Live Playground)
In JavaScript classes, instance methods are functions that are attached to class instances and can be called on those instances. In this tutorial, we'll explore the syntax and usage of instance methods in JavaScript classes.
Instance Method Syntax
Instance methods are defined within the class body as regular methods without the static
keyword. They are usually placed after the constructor method:
class Car {
constructor(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
}
displayInfo() {
console.log(`Make: ${this.make}, Model: ${this.model}, Year: ${this.year}`);
}
}
In this example, we've defined an instance method called displayInfo()
that logs the car's make, model, and year.
Using Instance Methods
To call an instance method, use the class instance followed by the method name and a pair of parentheses ()
:
const myCar = new Car('Toyota', 'Camry', 2020);
myCar.displayInfo(); // Make: Toyota, Model: Camry, Year: 2020
In this example, we've created a new Car
instance and called the displayInfo()
method on it.
Conclusion
In this tutorial, we learned about instance methods in JavaScript classes, their syntax, and usage. Instance methods allow you to define reusable functionality for your class instances, which makes your code more organized and easier to maintain.