Objects: Accessing a property of the object inside a method using `this`

Inside a method defined using a function() {} syntax we have access to the object instance by using this.

This is one of the concepts that confuse JavaScript developers the most.

this is a keyword that has different values depending on where it’s used, but there’s just one place where it makes sense to use this: INSIDE OBJECT METHODS.

A method, as you know, is a function attached to an object.

You know that functions have two forms:

  • regular functions
  • arrow functions

If you need to reference the object instance from within a method, you can’t use arrow functions. You have to use regular functions.

That’s one of the few places where regular functions can’t be replaced with arrow functions.

In the following example, we have access to the brand and model properties values using this.brand and this.model:

const car = {
  brand: "Ford",
  model: "Fiesta",
  start: function () {
    console.log(`Started
          ${this.brand} ${this.model}`)
  },
}

car.start()
//Started Ford Fiesta

It’s very important to note this distinction between regular functions and arrow functions: we don’t have access to this if we use an arrow function:

const car = {
  brand: "Ford",
  model: "Fiesta",
  start: () => {
    console.log(`Started
      ${this.brand} ${this.model}`)
  },
}

car.start()
//'Started undefined undefined'

This is because arrow functions are not bound to the object, and that’s why regular functions are often used as object methods.

Lessons in this unit:

0: Introduction
1: How to create an object
2: Object properties
3: Objects are passed by reference
4: Methods
5: Passing objects as function arguments or returning objects from a function
6: ▶︎ Accessing a property of the object inside a method using `this`
7: Object destructuring
8: Cloning objects
9: Sort an array of objects by a property value
10: Merging two objects into one
11: apply, call, bind