Na's Blog

Javascript: Understand "this" and "apply", "call", "bind" Methods In Function Calls

In the context of function, this is determined by how a function is called. For example:

const student = {
  name: "Ann",
  study: function() {
    return `${this.name} is studying.`
  }
}
console.log(student.study()) // 'Ann is studying.'

When we write student.study(), we say study function is called/accessed on the student object, therefore, this here refers to the student object.

Now we may want to save the student.study function to a variable, like below:

const studentStudy = student.study
console.log(studentStudy())  // ' is studying.'

This time, however, this.name didn't print out anything. The reason is when we call the function without the object it is called on, this loses its context. In this example, we assign student.study(the function) to a new variable, and when we call the function studentStudy, there's no object associated with it, therefore, this doesn't refer to anything anymore. In strict mode, it becomes null or undefined.(In non-strict mode, it will be the globalThis)

How do we get "this" back? By using apply, call, and bind methods, we can explicitly call a function with a given this value.

Continue with the same example:

// 'Using call method...Ann is studying.'
console.log(`Using call method...${studentStudy.call(student)}`)
// 'Using apply method...Ann is studying.
console.log(`Using apply method...${studentStudy.apply(student)}`)

Instead of invoking the studentStudy function, we use call or apply to specify the object the function will be called on, which is also the this value. Now we can get this.name again.

We can also use bind method, and it returns a new function with the specified this value binded.

const binded = studentStudy.bind(student)
console.log(binded())  // 'Ann is studying.'

The difference between apply, call and bind is, apply and call invoke the function, but bind returns a new function.

These methods also accept arguments of the function, which can be very useful. I will write about it in another article.