~/hackweb.dev
JavaScript Object Methods & this
Quiz
...

JavaScript Object Methods & this

beginner · updated Tue Sep 08 2026Contribute

Master object methods, the this keyword, and method shorthand.

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

  1. Use method shorthand — cleaner syntax
  2. Return this for chaining — enables fluent APIs
  3. Avoid arrow functions in methodsthis won’t work correctly

Common Mistakes

  1. Arrow functions as methodsthis points to wrong object
  2. Forgetting return this — breaks method chaining
  3. this in nested functionsthis changes context
  4. Not handling edge cases — check for null/undefined inputs