JavaScript Object Methods & this
Add functions to objects and understand the this keyword.
Object Methods
Functions inside objects are called methods:
let person = {
name: "John",
greet() {
return `Hello, I'm ${this.name}!`;
}
};
person.greet(); // "Hello, I'm John!"
The this Keyword
this refers to the object that called the method. It’s determined at call time, not definition time.
Method Chaining
Return this to enable chaining:
let calculator = {
value: 0,
add(n) { this.value += n; return this; },
subtract(n) { this.value -= n; return this; },
getResult() { return this.value; }
};
calculator.add(10).subtract(3).getResult(); // 7
Complete Example: Bank Account
let bankAccount = {
owner: "John",
balance: 1000,
transactions: [],
deposit(amount) {
if (amount > 0) {
this.balance += amount;
this.transactions.push({ type: "deposit", amount });
}
return this;
},
withdraw(amount) {
if (amount > 0 && amount <= this.balance) {
this.balance -= amount;
this.transactions.push({ type: "withdrawal", amount });
}
return this;
},
getBalance() {
return this.balance;
}
};
bankAccount.deposit(500).withdraw(200);
bankAccount.getBalance(); // 1300
Complete Example: Task Manager
let taskManager = {
tasks: [],
nextId: 1,
addTask(title, priority = "medium") {
this.tasks.push({ id: this.nextId++, text: title, priority, done: false });
return this;
},
complete(id) {
let task = this.tasks.find((t) => t.id === id);
if (task) task.done = true;
return this;
},
getStats() {
return {
total: this.tasks.length,
completed: this.tasks.filter((t) => t.done).length
};
}
};
taskManager.addTask("Learn JS", "high").addTask("Build project").complete(1);
taskManager.getStats(); // { total: 2, completed: 1 }
Best Practices
- Use method shorthand — cleaner syntax
- Return
thisfor chaining — enables fluent APIs - Avoid arrow functions in methods —
thiswon’t work correctly
Common Mistakes
- Arrow functions as methods —
thispoints to wrong object - Forgetting
return this— breaks method chaining thisin nested functions —thischanges context- Not handling edge cases — check for null/undefined inputs