Sikau

JavaScript · Day 39 · about 25 min

Methods and this

Objects that can do things.

Objects with actions

A bank account doesn't just have a balance — you can deposit into it. Objects can hold functions too. A function inside an object is called a method, and it can use the word this to mean "my own object".

Methods

const account = {
  owner: "Sita",
  balance: 1000,
  deposit(amount) {
    this.balance += amount;
  },
  report() {
    return `${this.owner} has Rs ${this.balance}`;
  },
};

account.deposit(500);
console.log(account.report());

"My": this is like the word "my". When Sita's account says "add to my balance", it means Sita's — not anybody else's.

Use the name() { … } style for methods. Arrow functions don't get their own this, so they're a poor fit here.

The rest of this lesson

  • Data and behaviour togetherexplain
  • Predict the outputpredict
  • Who is this?predict
  • Parts of an objectmatch
  • Your turnwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 68 lessons of JavaScript