0
0
Javascriptprogramming~5 mins

Instance methods in Javascript

Choose your learning style9 modes available
Introduction

Instance methods let objects do actions using their own data. They help keep code organized and easy to understand.

When you want each object to have its own behavior based on its data.
When you create many objects from the same blueprint and want them to act similarly but with their own values.
When you want to group related functions inside an object for clarity.
When you want to change or use the data inside an object safely.
When you want to reuse code by calling methods on different objects.
Syntax
Javascript
class ClassName {
  methodName() {
    // code using this.property
  }
}

Instance methods are defined inside a class and use this to access object data.

You call instance methods on an object created from the class.

Examples
This example shows a simple instance method bark that prints a sound. We call it on the myDog object.
Javascript
class Dog {
  bark() {
    console.log('Woof!');
  }
}

const myDog = new Dog();
myDog.bark();
This method uses this.name to access the object's data and print a greeting.
Javascript
class Person {
  constructor(name) {
    this.name = name;
  }
  greet() {
    console.log(`Hello, my name is ${this.name}`);
  }
}

const alice = new Person('Alice');
alice.greet();
Sample Program

This program creates a Car object with make and year. The displayInfo method prints these details.

Javascript
class Car {
  constructor(make, year) {
    this.make = make;
    this.year = year;
  }
  displayInfo() {
    console.log(`Car: ${this.make}, Year: ${this.year}`);
  }
}

const myCar = new Car('Toyota', 2020);
myCar.displayInfo();
OutputSuccess
Important Notes

Always use this inside instance methods to refer to the current object.

Instance methods can access and change object properties.

Do not call instance methods without creating an object first.

Summary

Instance methods are functions inside classes that work with object data.

They help objects perform actions using their own information.

You call instance methods on objects created from the class.