Instance Methods
What you'll learn: How to define reusable behavior on class instances by adding methods that operate on each object's data.
What Are Instance Methods?
Instance methods are functions defined inside a class that can be called on any object created from that class. Unlike instance properties (which hold data), instance methods hold behavior—they describe what an object can do.
When you define a method inside a class body (outside the constructor), JavaScript automatically adds it to the class's prototype. This means all instances share the same method definition, which is memory-efficient. Each object doesn't get its own copy of the method—they all point to the same function via the prototype chain.
Defining Instance Methods
Simply write a function inside the class body:
class BankAccount {
constructor(balance) {
this.balance = balance;
}
deposit(amount) {
this.balance = this.balance + amount;
}
getBalance() {
return this.balance;
}
}
const myAccount = new BankAccount(100);
myAccount.deposit(50);
console.log(myAccount.getBalance()); // 150
Here, deposit and getBalance are instance methods. They can access instance properties using this, which refers to the specific object calling the method.
Why Methods Live on the Prototype
Under the hood, deposit and getBalance are stored on BankAccount.prototype, not directly on myAccount. When you call myAccount.deposit(50), JavaScript finds deposit by walking up the prototype chain. This sharing means if you create 1,000 accounts, they all use the same deposit function—not 1,000 copies.
Key Takeaway: Instance methods define shared behavior for all objects of a class, stored efficiently on the prototype and accessible via this to operate on each instance's unique data.