Methods: functions inside objects
So far your objects only stored data. But they can act too: a property whose value is a function is called a method, and it's what lets the object "do things" instead of just holding them:
const calculator = {
add: function (a, b) {
return a + b;
},
// shorthand syntax (ES6):
subtract(a, b) {
return a - b;
},
};
console.log(calculator.add(2, 3)); // 5
console.log(calculator.subtract(7, 4)); // 3
The this keyword
And how does a method reach its own object's data? With this. Inside a method,
this points to the object through which the method is called. In the normal
case, object.method(), that object is the one to the left of the dot, so
this is like saying "myself": it gives you access to its other properties.
const person = {
name: "Ana",
greet() {
return "Hi, I'm " + this.name;
},
};
console.log(person.greet()); // "Hi, I'm Ana"
⚠️ Classic trap:
thisdoes not depend on where the method is defined, but on how it is called. If you "pull" the method out of its object and call it on its own,thisis left orphaned and stops pointing to that object:const f = person.greet; f(); // this is no longer person → this.name would be undefinedWe'll see how to fix
this(withbind, or using classes) in the OOP module.
Important: arrow functions don't have their own
this, which is why for object methods that usethisthe normal or shorthand syntax is usually preferred, not the arrow.
Examples
A bank account that modifies itself with this
const account = {
balance: 100,
deposit(amount) {
this.balance = this.balance + amount;
return this.balance;
},
};
console.log(account.deposit(50)); // 150
console.log(account.balance); // 150