How do you add a method to a class?
1. Regular (Public) Method
A method available on every instance of the class:
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:
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:
class MathUtils {
static square(n) {
return n * n;
}
}
console.log(MathUtils.square(5)); // 25Instances (
new MathUtils()) do not have access tostaticmethods.
4. Getter and Setter
Used to "disguise" properties as methods:
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.priceactually callsget price(), assigningp.price = ...callsset price().
5. Private Methods (#methodName)
Inaccessible from outside, only from within the class:
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 method6. Field Methods (Arrow Functions)
If you want a method to preserve the this context, you can declare it as a field:
class Button {
label = "Click me";
handleClick = () => {
console.log(`Clicked: ${this.label}`);
};
}
const b = new Button();
b.handleClick(); // Clicked: Click meSuch methods don't lose this, even when passed as a callback:
setTimeout(b.handleClick, 1000); // everything works correctlySummary
| Method Type | Syntax | Accessibility | Notes |
|---|---|---|---|
| Regular | method() {} | Via an instance | Shared by all instances |
| Static | static method() {} | Via the class itself | Not visible on instances |
| Getter / setter | get name() {}, set name(v) {} | Like a property | Access can be controlled |
| Private | #method() {} | Only inside the class | Full encapsulation |
| Field method (arrow) | method = () => {} | Via an instance | Doesn't lose this |
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.