DEV Community

Cover image for bind(), call() & apply() in JS
Saurabh sharma
Saurabh sharma

Posted on

bind(), call() & apply() in JS

In this you will get a deep knowledge about how call(), bind() and apply works.

These methods are available to every function in JavaScript. which are all used to change the scope of what this is equal to inside of a function or a method. Let's see the following examples.

bind()

We will start with a simple example of an object that has a method on it. With bind(), we can tell the JavaScript engine where to look for this.

const person = {
  name: "Saurabh",
  myFunction: function () {
    return(`Hello ${this.name}`)
  }
}

function greetPerson() {
  console.log(this.myFunction())
}

const bindPerson = greetPerson.bind(person)

bindPerson();
//Expected Output :- Hello Saurabh
Enter fullscreen mode Exit fullscreen mode

Things to notice here are :

  • The bind() creates bindPerson, and a copy of the greetPerson function.
  • bindPerson when called will have it's this variable pointing to the person object

call()

The call() calls a function with a given this value and arguments provided individually.

call() essentially does the same thing as bind() except that call() actually executes the function

const Saurabh = {
  name: "Saurabh",
  myFunction: function () {
    return(`Hi, I'm ${this.name}`)
  }
}

function callingFunction(age, hobby) {
  console.log(`${this.myFunction()}, my age is ${age} and I 
  like to ${hobby}`);
}

callingFunction.call(Saurabh, 26, 'reading');

// Expected Output :- Hi, I'm Saurabh, my age is 26 and I like reading

Enter fullscreen mode Exit fullscreen mode

apply()

call() and apply() do the exact same thing except that call() expects all parameters to be passed in individually, but apply() expects all additional parameters to be passed as an array.
so this what our existing sample code will look like :

const Saurabh = {
  name: "Saurabh",
  myFunction: function () {
    return(`Hi, I'm ${this.name}`)
  }
}

function applyingFunction(age, hobby) {
  console.log(`${this.myFunction()}, my age is ${age} and I like 
  ${hobby}`)
}

applyingFunction.apply(Saurabh, ``[26, 'Reading']``)

// Expected Output :- Hi, I'm Saurabh, my age is 26 and I like Reading
Enter fullscreen mode Exit fullscreen mode

Hope you find it useful and learned something new from it.

Top comments (0)