call, apply and bind in javascript

call, apply and bind methods are used to invoke a method on specific object

call

call allows you to execute the given method on given object. This way object can call third party method.

apply

apply method is same as call with only one difference - apply method takes arguments in the form of array.

bind

with bind method, called method does not return immediately. But we get other method which we can call later with extra parameters when available.

let user1 = {"name":"sagar", "id":"123"}

let user2 = {"name":"Donald", "id":"444"}

let printName = function (){
    console.log('User details ', this.name, arguments)
}


//call
printName.call(user1,"C", "C++")
printName.call(user2,"Java", "Python")

//apply
printName.apply(user1,["C", "C++"])
printName.apply(user2,["Java", "Python"])

//bind
let f1 = printName.bind(user1,"C", "C++")

// f1();

Web development and Automation testing

solutions delivered!!