Learn how to add methods to JavaScript objects and understand how the this keyword behaves in different contexts.
Day 10 of 30 | Stage: Data Structures | Estimated time: 40-50 minutes
- Add functions as object methods
- Understand how the this keyword behaves inside methods
- Use Object.keys(), Object.values(), and Object.entries()
- Recognize how arrow functions handle this differently
const calculator = {
value: 0,
add(amount) {
this.value += amount;
return this.value;
},
};
console.log(calculator.add(5)); // 5
console.log(calculator.add(10)); // 15Inside a regular method, this refers to the object the method was called on.
const person = {
name: "Lucia",
greet() {
return `Hi, I am ${this.name}`;
},
};
console.log(person.greet()); // "Hi, I am Lucia"If you copy a method out of its object, this loses its connection.
const greetFn = person.greet;
// console.log(greetFn()); // "Hi, I am undefined" in strict contexts, or an errorThis happens because this depends on how a function is called, not where it was defined.
Arrow functions do not have their own this, they use this from the surrounding scope where they were defined. This makes them unsuitable as object methods that rely on this.
const counter = {
count: 0,
increment: function () {
this.count++; // works, regular function gets its own `this`
},
incrementArrow: () => {
// `this` here does NOT refer to `counter`
// this.count++; would not work as expected
},
};
counter.increment();
console.log(counter.count); // 1const car = { brand: "Honda", model: "Civic", year: 2022 };
console.log(Object.keys(car)); // ["brand", "model", "year"]
console.log(Object.values(car)); // ["Honda", "Civic", 2022]
console.log(Object.entries(car));
// [["brand", "Honda"], ["model", "Civic"], ["year", 2022]]
Object.entries(car).forEach(([key, value]) => {
console.log(`${key}: ${value}`);
});const original = { a: 1, b: 2 };
const copy = { ...original, c: 3 }; // spread syntax, covered fully on Day 18
console.log(copy); // { a: 1, b: 2, c: 3 }
console.log(original); // unchanged: { a: 1, b: 2 }Use regular function syntax (
methodName() {}) for object methods that rely onthis, and reserve arrow functions for callbacks or cases where you intentionally want to inheritthisfrom the surrounding scope.
- Methods are functions stored as object properties
thisinside a regular method refers to the object it was called on- Arrow functions do not bind their own
this, which can cause bugs if used as object methods Object.keys(),Object.values(), andObject.entries()let you iterate over an object's data
Create an object wallet with a balance and methods deposit(amount) and withdraw(amount) that update the balance using this.
Simulate a simple bank account object with deposit, withdraw, and transaction history methods.
Open the Day 10 project brief →
← Day 09: Objects · Course Home · Day 11: Strings in Depth →