Skip to main content

Command Palette

Search for a command to run...

Call , Apply , Bind

Updated
2 min read
Call , Apply , Bind
A

In the process of becoming a full stack developer

Method Borrowing

Method borrowing, also known as function borrowing, as its name tells, it is a way of using member function of one object to another object .

Here we have three methods , that we can use for implementing Method Borrowing -

  • call
  • apply
  • bind

Call Method

So what is call ?

By using call() method we can do method borrowing .

  • function : shared function
  • object1 : Whose function is for sharing.
  • object2 : Who is using object1
  • args : arguments

Syntax for using call()-

object1.function.call(object2 , ...args)

for example : lets assume your father have a car . he is the owner and use the car for going to office, You and your friends made a plan for a road trip and need a car , so you call dad and borrow the car for your purpose , but here the main purpose of car is transportation , only the route changed .

so in this story, your father is object1 and you are object2 and the function is driving and the arguments are the routes.

Screenshot from 2021-09-14 21-20-18.png

output :

Screenshot from 2021-09-14 21-22-58.png

anyone can use the car father , mother , son daughter everyone.

so now its clear why we use call method .

bind and apply also share the same story .

Now lets discuss , apply()-

Apply Method

apply and call are same , the only difference is the way of passing arguments;

  • function : shared function
  • object1 : Whose function is for sharing.
  • object2 : Who is using object1
  • args : arguments

Syntax for using apply()-

object1.function.apply(object2 , [args1 ,args2,......argsN])

Here we have pass the arguments in a array and everything is same as call(). lets run the same code with apply()

Screenshot from 2021-09-14 21-38-03.png

output :

Screenshot from 2021-09-14 21-40-33.png

Bind method

The JavaScript Function bind() method is used to create a new function. When a function is called, it has its own this keyword set to the provided value, with a given sequence of arguments.

Syntax for using bind() : let see the same code with bind() method :

  • function : shared function
  • object1 : Whose function is for sharing.
  • object2 : Who is using object1
  • args : arguments
  • callBackFn : bind method return a function

Syntax for using bind()-

callBackFn = object1.function.call(object2 , ...args)

callBackFn()

let see the same operation with bind()

Screenshot from 2021-09-14 21-51-04 (1).png

output :

Screenshot from 2021-09-14 21-51-23 (1).png

here bind() returns a callback function .