Object Methods and This

Updated · 6 min read

A method is a function stored as a property of an object. Methods give objects behavior: a fee account can addPayment, report its balance, or describe itself. Inside a method, the keyword this refers to the object the method was called on, which lets one method definition work with that object's own data. This lesson covers the basics of this that every object needs; the full set of rules is in the this keyword lesson later.

In One Minute

  • A method is a function as a property: { describe() { ... } } (method shorthand) or { describe: function () { ... } }.
  • Call it with a dot: account.describe().
  • Inside, this is the object before the dot in the call. this.balance reads that object's balance.
  • this is decided by how the method is called, not where it was written. Detach it (const f = account.describe) and this is lost.
  • Don't write methods as arrow functions: arrows don't get their own this.

Defining Methods

Syntax

syntax.js
const object = {
  methodName(parameters) {   // method shorthand (ES2015)
    // this refers to object when called as object.methodName()
  },
};

Example

method.js▶ Try it
const account = {
  owner: "Navika",
  balance: 450,
  addPayment(amount) {
    this.balance -= amount;
    return this.balance;
  },
  describe() {
    return `${this.owner} owes $${this.balance}`;
  },
};
 
console.log(account.describe());
account.addPayment(200);
console.log(account.describe());
Output
Navika owes $450
Navika owes $250

Explanation: in account.addPayment(200), the object before the dot is account, so inside the method this is account, and this.balance -= amount updates its balance. describe reads the updated value.

The older long form describe: function () { ... } does the same thing. Method shorthand is shorter and is what you'll see in modern code.

How this Is Decided

this isn't fixed when the method is written. It is set each time the function is called, based on the call:

this-call.js▶ Try it
function describe() {
  return `${this.owner}: $${this.balance}`;
}
 
const navika = { owner: "Navika", balance: 250, describe };
const advitha = { owner: "Advitha", balance: 45, describe };
 
console.log(navika.describe());
console.log(advitha.describe());
Output
Navika: $250
Advitha: $45

Explanation: one function, shared by two objects. Called as navika.describe(), this is navika; called as advitha.describe(), this is advitha. This is how one method can serve many objects, which is exactly what classes do behind the scenes.

The Lost this Bug

Because this depends on the call, taking a method off its object loses it. This happens whenever a method is passed as a callback:

lost-this.js▶ Try it
const account = {
  owner: "Srihitha",
  describe() {
    return `Owner: ${this?.owner}`;
  },
};
 
console.log(account.describe());
 
const detached = account.describe;
console.log(detached());
 
const bound = account.describe.bind(account);
console.log(bound());
 
console.log([1].map(() => account.describe())[0]);
Output
Owner: Srihitha
Owner: undefined
Owner: Srihitha
Owner: Srihitha

Explanation: detached() is a plain call with nothing before the dot, so this isn't account and owner is missing. Two common fixes:

  • bind creates a new function with this permanently set: account.describe.bind(account).
  • Wrap it in an arrow that calls the method properly: () => account.describe().

You'll hit this most with event listeners and timers: setTimeout(account.describe, 1000) loses this; setTimeout(() => account.describe(), 1000) doesn't.

Don't Use Arrows as Methods

Arrow functions don't have their own this; they use the this of the surrounding code. As a method, that means they don't see the object:

arrow-method.js▶ Try it
const account = {
  owner: "Advitha",
  arrowDescribe: () => `Owner: ${this?.owner}`,
  methodDescribe() {
    return `Owner: ${this.owner}`;
  },
};
 
console.log(account.arrowDescribe());
console.log(account.methodDescribe());
Output
Owner: undefined
Owner: Advitha

Arrows are excellent inside methods (for callbacks), because they keep the method's this:

arrow-inside.js▶ Try it
const tracker = {
  currency: "USD",
  amounts: [120, 85],
  labels() {
    return this.amounts.map((a) => `${a} ${this.currency}`);
  },
};
 
console.log(tracker.labels());
Output
['120 USD', '85 USD']

Getters and Setters

A getter is a method that runs when a property is read; a setter runs when it is assigned. They let a value be calculated, or checked, while still looking like a plain property:

getters.js▶ Try it
const account = {
  fees: [400, 85],
  payments: [200],
  get balance() {
    const owed = this.fees.reduce((a, b) => a + b, 0);
    const paid = this.payments.reduce((a, b) => a + b, 0);
    return owed - paid;
  },
  set lastPayment(amount) {
    if (!(amount > 0)) throw new RangeError("Payment must be positive");
    this.payments.push(amount);
  },
};
 
console.log(account.balance);
account.lastPayment = 150;
console.log(account.balance, account.payments);
Output
285
135 [200, 150]

Explanation: account.balance has no parentheses, but it runs the getter and always returns an up-to-date value. Assigning account.lastPayment = 150 runs the setter, which validates the amount and records it. Getters and setters are covered further with classes, where they are most common.

In Practice

The Fee Tracker's account object groups the data and every operation on it, and uses an arrow wrapper where a method is passed to a timer:

account.js▶ Try it
const account = {
  owner: "Navika",
  payments: [],
  addPayment(amount, date) {
    this.payments.push({ amount, date });
    return this;
  },
  get totalPaid() {
    return this.payments.reduce((sum, p) => sum + p.amount, 0);
  },
  summary() {
    return `${this.owner} paid $${this.totalPaid} in ${this.payments.length} payments`;
  },
};
 
account.addPayment(200, "01/05/2026").addPayment(150, "02/05/2026");
console.log(account.summary());
 
setTimeout(() => console.log("Later:", account.summary()), 0);
Output
Navika paid $350 in 2 payments
Later: Navika paid $350 in 2 payments

addPayment returns this, which allows method chaining: account.addPayment(...).addPayment(...).

Common Mistakes

Arrow functions as methods. this won't be the object. Use method shorthand.

Passing a method as a callback. button.addEventListener("click", account.save) loses this. Use () => account.save().

Forgetting this. Inside a method, balance refers to a variable named balance, not the property. Write this.balance.

Calling a getter with parentheses. account.balance() throws TypeError: account.balance is not a function, because the getter returns a number.

Practice

Challenge: Create a counter object with a count property and methods increment(), reset() and a getter isZero. increment should return this so calls can be chained.

Show solution
counter.js▶ Try it
const counter = {
  count: 0,
  increment() {
    this.count += 1;
    return this;
  },
  reset() {
    this.count = 0;
    return this;
  },
  get isZero() {
    return this.count === 0;
  },
};
 
counter.increment().increment().increment();
console.log(counter.count, counter.isZero);
console.log(counter.reset().isZero);
Output
3 false
true

Quick check: Methods and this

3 questions
1In account.describe(), what is this inside describe?
2Why does const f = account.describe; f(); lose this?
3Why shouldn't object methods be arrow functions?

Key Takeaways

PatternCode
Method shorthand{ describe() { return this.name; } }
ChainingaddPayment() { ...; return this; }
Keep this in a callback() => obj.method()
Bind permanentlyobj.method.bind(obj)
Getterget balance() { return ...; }

Was this tutorial helpful?

Lesson 38 of 139