Object Methods and This
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,
thisis the object before the dot in the call.this.balancereads that object's balance. thisis decided by how the method is called, not where it was written. Detach it (const f = account.describe) andthisis lost.- Don't write methods as arrow functions: arrows don't get their own
this.
Defining Methods
Syntax
const object = {
methodName(parameters) { // method shorthand (ES2015)
// this refers to object when called as object.methodName()
},
};Example
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());Navika owes $450
Navika owes $250Explanation: 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:
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());Navika: $250
Advitha: $45Explanation: 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:
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]);Owner: Srihitha
Owner: undefined
Owner: Srihitha
Owner: SrihithaExplanation: detached() is a plain call with nothing before the dot, so this isn't account and owner is missing. Two common fixes:
bindcreates a new function withthispermanently 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:
const account = {
owner: "Advitha",
arrowDescribe: () => `Owner: ${this?.owner}`,
methodDescribe() {
return `Owner: ${this.owner}`;
},
};
console.log(account.arrowDescribe());
console.log(account.methodDescribe());Owner: undefined
Owner: AdvithaArrows are excellent inside methods (for callbacks), because they keep the method's this:
const tracker = {
currency: "USD",
amounts: [120, 85],
labels() {
return this.amounts.map((a) => `${a} ${this.currency}`);
},
};
console.log(tracker.labels());['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:
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);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:
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);Navika paid $350 in 2 payments
Later: Navika paid $350 in 2 paymentsaddPayment 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
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);3 false
trueKey Takeaways
| Pattern | Code |
|---|---|
| Method shorthand | { describe() { return this.name; } } |
| Chaining | addPayment() { ...; return this; } |
Keep this in a callback | () => obj.method() |
| Bind permanently | obj.method.bind(obj) |
| Getter | get balance() { return ...; } |
Was this tutorial helpful?