DEV Community

Cover image for JavaScript call, bind, and apply methods
Taslan Graham
Taslan Graham

Posted on • Updated on • Originally published at taslangraham.com

JavaScript call, bind, and apply methods

Full post available here.

Each JavaScript function has access to the this keyword. The this keyword references the object to which the function belongs (remember, everything in JS is an Object).

This sounds straightforward enough but, things can quickly get tricky when working with this. Why? The value of this is determined by how/where the function was executed:

  • In a method, this refers to the owner object.
  • Alone, this refers to the global object.
  • In a function, this refers to the global object.
  • In a function, in strict mode, this is undefined
  • In an event, this refers to the element that received the event.

This means that if we are not careful we can lose the scope of this.

Luckily, all JavaScript function object has access to some very special methods which we can use to explicitly state what this should reference. These methods are bind(), call(), & apply().


Bind


The bind() method creates a new function that, when called, has its this keyword reference the provided value.


function greeting() {
  console.log(`${this.firstName} says hi!`)
}

const john = {
  firstName: 'John',
  lastName: 'Doe',
  age: 20
};

const johnGreeting = greeting.bind(john);
Enter fullscreen mode Exit fullscreen mode


Above, we created the function greeting, then on line 11, we used the bind method to tell the function that the this keyword should point to the object john.

This then returns a new function which we store inside johnGreeting. We can then execute johnGreeting.

johnGreeting(); // John says hi!
Enter fullscreen mode Exit fullscreen mode

The bind() method can also accept arguments. These will come after the this argument. Here's an example:

function greeting(country) {
  console.log(`${this.firstName} says hi! from ${country}`)
}

const john = {
  firstName: 'John',
  lastName: 'Doe',
  age: 20
};
Enter fullscreen mode Exit fullscreen mode

Here our greeting function now accepts an argument, country. We can now pass an additional parameter to the bind() method.

const johnGreeting = greeting.bind(john, 'Jamaica');

johnGreeting(); // John says hi! from Jamaica

Enter fullscreen mode Exit fullscreen mode


Call


The call() method calls a function with a given this. The difference between the bind() and the call() is that the call() method does not create a new function, instead it immediately executes the function. Here's an example:

function printName() {
  console.log(`${this.firstName} ${this.lastName}`);
}

student = {
  firstName: 'Taslan',
  lastName: 'Graham'
};

printName.call(student);// Taslan Graham
Enter fullscreen mode Exit fullscreen mode

Here we created a function, printName, and an object student. We then, on line 10, executed the printName function by calling the call() method on it and passing student object as the this that printName should use.

Similarly to the bind() method, the call() method can accept arguments.

function printName(age) {
  console.log(`Name: ${this.firstName} ${this.lastName}, Age:${age}`);
}

student = {
  firstName: 'Taslan',
  lastName: 'Graham'
};

printName.call(student, 24); // Name: Taslan Graham, Age:24

Enter fullscreen mode Exit fullscreen mode

Here our greeting function now accepts an argument, age. We can now pass an additional parameter to the call() method.


Apply


Like the the methods above, the apply() method calls a function with a given this. It is very similar to the call() method, the difference being that the apply() method accepts arguments as an array.

const student = {
  details: function () {
    return `${this.name}, ${this.class}`;
  }
}

const graham = {
  name: "Graham",
  class: "Intro to Computer Science",
}

console.log(student.details.apply(graham)); // Graham, Intro to Computer Science
Enter fullscreen mode Exit fullscreen mode

Here we have an object, student, which has a method called details.

We also have another object, graham, this object does not have the details method, but we used the apply() method to tell the the details() method of student that its this value should point to the the graham object.

Note: bind() & call() can be used in the way apply() is used aboved.

The apply() method can also accept additional arguments. These are passed as an array.

function printName(...args) {
  console.log(`Name: ${this.firstName} ${this.lastName}, Age:${args[0]} Country: ${args[1]}`);
}

student = {
  firstName: 'Taslan',
  lastName: 'Graham'
};

const age = 24;
const country = "Jamaica";
printName.apply(student, [age, country]); // Name: Taslan Graham, Age:24 Country: Jamaica
Enter fullscreen mode Exit fullscreen mode

Above, we passed an array holding age and country to our printName function. We use the rest parameters to capture this array, then we print the values from their respective indexes.



As you can see, the bind(), call(), bind() are very powerful when we want want to determine what the this value inside of a function should be. They all work similarly but with there own unique differences.

The bind() method creates a new function with the this value provided to it. While the call() method immediately executes a function with the given this value. Similarly to the call() method, apply() immediately executes the function with the given this value but, it accepts its arguments as an array.

Hope you found this helpful. Be sure to leave comments below on the interesting ways you've used call(), bind(), and apply().

Until next time, think, learn, create, repeat!

Top comments (1)

Collapse
 
fericoder profile image
Fariborz

Excellent❤❤❤
Just please send me an example of using this point to my email or right here ..
"Note: bind() & call() can be used in the way apply() is used aboved."
Thank you for this article ...❤❤❤