Methods and this
Functions inside objects.
Objects can hold functions too. A function stored in an object is called a method. Methods let an object do things, like a bank account that can deposit money, or a dog that can bark.

- Objects can hold functions
- Those are methods
- Objects that do things
this means this object
Deposit is a method. Inside it, the keyword this means the object the method was called on, so this dot balance is the account's own balance. We call methods with a dot, just like console dot log. Run it.
const account = {
owner: "Ana",
balance: 100,
deposit(amount) {
this.balance += amount;
return this.balance;
},
describe() {
return `${this.owner} has $${this.balance}`;
},
};
account.deposit(50);
console.log(account.describe());Ana has $150
Arrow functions and this
Here's the deeper difference we promised. Arrow functions don't have their own this. Inside an arrow function, this means whatever it meant outside. So for methods that use this, use the short method syntax, like deposit, round brackets, curly braces. Not an arrow.
| key | value |
|---|---|
| Method | a function in an object |
| this | the object it's called on |
| Short syntax | deposit(amount) { } |
| Arrows | no own this |
Methods that change the object
Methods can change their own object, using this. Here, a counter object has an increase method and a reset method. Each method reads and writes this dot count. And because increase returns this, we can chain calls one after another. Run it.
const counter = {
count: 0,
increase() {
this.count++;
return this;
},
reset() { this.count = 0; },
};
counter.increase().increase().increase();
console.log(counter.count);
counter.reset();
console.log(counter.count);3 0
Summary
Methods are functions inside objects, and this refers to the object they're called on. Next, looping through an object's properties.
Key takeaways- method() { }
- this.property
- Avoid arrows for methods