Skip to main content

How do you add a method to a class?

1. Regular (Public) Method

A method available on every instance of the class:

javascript
class User { constructor(name) { this.name = name; } greet() { console.log(`Hi, ${this.name}!`); } } const u = new User("Alice"); u.greet(); // Hi, Alice!

Such methods are automatically added to User.prototype, meaning they are shared across all instances (rather than being recreated for every object).


2. Adding a Method After the Class Is Declared

You can add a method to a class's prototype manually, after it has been declared:

javascript
class User { constructor(name) { this.name = name; } } // Add a method afterward User.prototype.sayBye = function () { console.log(`${this.name} says: bye!`); }; const u = new User("Alice"); u.sayBye(); // Alice says: bye!

This works because under the hood, a class is just a function with a prototype.


3. Static Method (static)

This kind of method is called directly on the class, not on an instance:

javascript
class MathUtils { static square(n) { return n * n; } } console.log(MathUtils.square(5)); // 25

Instances (new MathUtils()) do not have access to static methods.


4. Getter and Setter

Used to "disguise" properties as methods:

javascript
class Product { constructor(price) { this._price = price; } get price() { return this._price + " $"; } set price(value) { if (value < 0) throw new Error("Price cannot be negative"); this._price = value; } } const p = new Product(1000); console.log(p.price); // "1000 $" p.price = 1500; console.log(p.price); // "1500 $"

Accessing p.price actually calls get price(), assigning p.price = ... calls set price().


5. Private Methods (#methodName)

Inaccessible from outside, only from within the class:

javascript
class Account { #logBalance() { console.log(`Current balance: ${this.balance}`); } constructor(balance) { this.balance = balance; this.#logBalance(); // can only be called from here } } const acc = new Account(500); // acc.#logBalance(); Error: private method

6. Field Methods (Arrow Functions)

If you want a method to preserve the this context, you can declare it as a field:

javascript
class Button { label = "Click me"; handleClick = () => { console.log(`Clicked: ${this.label}`); }; } const b = new Button(); b.handleClick(); // Clicked: Click me

Such methods don't lose this, even when passed as a callback:

javascript
setTimeout(b.handleClick, 1000); // everything works correctly

Summary

Method TypeSyntaxAccessibilityNotes
Regularmethod() {}Via an instanceShared by all instances
Staticstatic method() {}Via the class itselfNot visible on instances
Getter / setterget name() {}, set name(v) {}Like a propertyAccess can be controlled
Private#method() {}Only inside the classFull encapsulation
Field method (arrow)method = () => {}Via an instanceDoesn't lose this

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.