Call, Apply and Bind in javascript

ยท

2 min read

If you are learning Javascript, then you must have heard about implicit binding, and explicit binding.

what is implicit binding ?

An object which has a function that can be called using (.) dot operator is an implicit binding. Let's see an example.

const name = {
firstName : "Walter",
lastName : "White",
printName : function() {
                     console.log(this.firstName+" "+this.lastName)
                             }
                         }

name.printName()  //implicit binding

// output :  Walter White

Now what is explicit binding?

Here call() is comes into the picture, Here we can make multiple objects having one function, and we get the output according to the multiple objects. So basically we write one function and borrow it for multiple objects, this is the function borrowing method.

Considering above example lets understand call()


const person  = {
firstName : "Bruce",
lastName : "Wayne"
}

name.printName.call(person) // first argument is object reference

// output : Bruce Wayne

another example, we can see first argument is object, and second argument is parameter from function itself.

function ask(person) {
console.log(person, "asked ", this.name)
}

const who = {
 name : "Butler"
}

ask.call(who, "Bruce");

//output : Bruce asked Butler

Lets see Apply()

so apply() same as call(), the only difference apply used when we have more than one parameter in function, we passed an array.

function whereYouLive(state, country){
console.log(this.firstName+" "+this.lastName+" lives in "+state+" " +country);
}

const name = {
firstName : "Bruce",
lastName : "Wayne"
}

whereYouLive.apply(name, ['Gotham' ,'US']) 

// Bruce Wayne lives in Gotham US

Bind()

This binds with given object. It returns a function that can be called/invoked later.

Here is an example


function printName(age) {
console.log(this.firstName+" "+this.lastName, age)
}

const name = {
firstName : "Bruce",
lastName : "Wayne"
}

const personWithAge = printName.bind(name, 60);

personWithAge() // Bruce Wayne 60

I hope these examples clear the above topics, if you have any queries please do comment. Until then keep coding ๐Ÿง‘โ€๐Ÿ’ป

ย