Basics

Instance methods are functions that are defined on the prototype of an object's class. They can be called on instances (objects) of that class, and have access to the properties of the instance through this keyword.

Here is an example of a class with an instance method:

class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }

  sayHello() {
    console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
  }
}

const person1 = new Person('John', 30);
person1.sayHello(); // "Hello, my name is John and I am 30 years old."

In this example, the Person class has a sayHello method that logs a greeting to the console. The method is defined on the class's prototype, so it can be called on any instance of the Person class.

Instance methods are useful for defining behaviour that is specific to an object and that requires access to the object's properties. They can also be overridden by subclasses to customize the behavior for specific types of objects.

Last updated