Link method call in JavaScript

In JavaScript, sometimes we can chain method calls as follows:

car.start().drive()

This is very convenient.

Instead of writing

car.start()
car.drive()

We can simplify the first line.

This can happen if each method returns the object itself. In other words, the implementation must look like this:

const car = {
  start: function() {
    console.log('start')
    return this
  },
  drive: function() {
    console.log('drive')
    return this
  }
}

It’s important to note that you cannot use the arrow function becausethisIn arrow functions used as object methods, they are not bound to object instances.

I like to use the arrow function all the time. This is one of the situations where you cannot use it.

Chaining method calls is very useful when you are not returning a set of values from a method, otherwise obviously you need to assign the method call to a variable and it cannot be chained:

const result = car.start()
if (result) {
  car.drive()
}

Download mine for freeJavaScript beginner's manual


More js tutorials: