JavaScript – Call(), Apply() and Bind() Methods Tutorial

The call(), apply() and bind() methods are very important in JavaScript. They give context to this keyword in object. In ES6 we can code an object like this with a function.

const person = {
    firstName: 'Adam',
    lastName: 'Sandler',
    fullName(){
        return this.firstName + ' ' + this.lastName
    }
}

Now if we call the fullName() method person.fullName() then it will give us ‘Adam Sandler’. But if we will make 2 objects with firstName and lastName and we want to use the fullName() method in person object, what should we do? ES6 gives us the ability to do so by introducing the call() method. 

const person1 = {
    firstName: 'John',
    lastName: 'Doe',
}

const person2 = {
    firstName: 'Mary',
    lastName: 'Doe',
}

person.fullName.call(person1)
person.fullName.call(person2)

This will show John Doe and Mary Doe as output. Why? Because the call() method will change the context of this from person to person1 and person2. 

Now the apply() method is the same but it will take an array as arguments. 

const obj = {name: 'Rameez'}
let greeting = function(a,b) {
    return `${a} ${this.name}. ${b}`;
}
console.log(greeting.apply(obj, ['Hello', 'How are you?'] ))

The apply() method is used to pass arguments to function. Math.max or Math.min takes numbers as arguments but using apply we can pass arrays to them. 

const numbers = [1,3,5,2,4]
let max = Math.max.apply(null, numbers);
console.log(max)

Third method is bind(). It binds an object with a method and creates a new method which we can call separately at another point in our code. 

const obj = {name: 'Rameez'}

let greeting = function(a,b) {
    return `${a} ${this.name}. ${b}`;
}

const bound = greeting.bind(obj)
console.log(bound('Hello', 'How are you?'))