Objects with behavior
An object groups data (properties) and behavior (methods). A method is simply a function stored as a property:
const account = {
balance: 100,
deposit(amount) {
this.balance += amount;
},
};
account.deposit(50);
console.log(account.balance); // 150
The this keyword
Inside a method, this refers to the object the method was called on.
That is why this.balance accesses the balance of that specific object.
this is dynamic: its value depends on how the function is called, not on
where it was defined. When you call account.deposit(50), this is account.
Arrow functions do not have their own
this: they inherit it from the surrounding context. That is why, for object methods, themethod() { ... }syntax is usually preferred.
Examples
An object with a method and this
const counter = {
value: 0,
increment() {
this.value++;
return this.value;
},
};
console.log(counter.increment());
console.log(counter.increment());