AI Hints
JavaScript · Lesson 60 of 138

Methods and this

Functions inside objects.

⏱ 2 min read▶ Video at 1:13:09🎓 Free
Watch this lesson in the JavaScript courseWatch on YouTube ↗Full JavaScript course

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.

Methods and this
From the video: Methods and this
  • 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.

app.jsjavascript
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());
Output
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.

keyvalue
Methoda function in an object
thisthe object it's called on
Short syntaxdeposit(amount) { }
Arrowsno 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.

app.jsjavascript
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);
Output
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
Next up: Looping Objects — Object.keys, entries