Lesson 29 +15 XP

Object Methods and this

Object Methods and this

A method is a function that lives inside an object. The this keyword refers to the object the method belongs to.

Creating methods

const person = {
  firstName: "Ada",
  lastName: "Lovelace",
  fullName: function() {
    return this.firstName + " " + this.lastName;
  }
};

Calling a method

person.fullName(); // "Ada Lovelace"

What is this?

Inside a method, this refers to the object that owns the method. It lets the method read the object's own properties.

A simpler example

const counter = {
  count: 0,
  increase: function() {
    this.count++;
  }
};
counter.increase();
counter.count; // 1

Method shorthand

Modern JavaScript lets you write methods without the function keyword:

const person = {
  firstName: "Ada",
  fullName() {
    return this.firstName;
  }
};

TL;DR

  • Methods are functions stored in objects.
  • this refers to the owning object.
  • Call a method with object.method().
  • Method shorthand omits the function keyword.