~/
hackweb.dev
JavaScript Object Methods & this
Quiz
⌘K
...
~/
/tutorials
/js/js-object-methods-this/edit
~ Contribute
Suggest a correction or improvement. The author reviews it before it goes live.
Loading...
Comment
0 / 300
Typo
Grammar
Broken link
Clarify
Code
en/tutorials/js/15js-object-methods-this
Write
Preview
Diff
# JavaScript Object Methods & this Add functions to objects and understand the `this` keyword. ## Object Methods Functions inside objects are called methods: ```javascript 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: ```javascript 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 ```javascript 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 ```javascript 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 1. **Use method shorthand** — cleaner syntax 2. **Return `this` for chaining** — enables fluent APIs 3. **Avoid arrow functions in methods** — `this` won't work correctly ## Common Mistakes 1. **Arrow functions as methods** — `this` points to wrong object 2. **Forgetting `return this`** — breaks method chaining 3. **`this` in nested functions** — `this` changes context 4. **Not handling edge cases** — check for null/undefined inputs
No changes yet
Reset to original
Submit suggestion
cancel