JavaScript — call(), apply() and bind()

CodeyMaze
3 min readOct 12, 2021

--

Call( ), apply( ) and bind( ) methods are very important and useful methods in JavaScript. Call( ) & apply( ) immediately invokes a function and bind( ) method returns a function that can be invoked later on.

  • Call( ) method invokes the function and allows us to pass parameters one by one.
  • Apply( ) method invokes the function and allows us to pass parameters as array.
  • Bind( ) method invokes the function and allows us to pass in an array and any number of parameters.

The call( ) method invokes a function with a given this value and parameters one by one.

In this example, we have called the sayHello function passing the context of a person1 and Hello as a parameter. This will take the firstname and lastname from person1 object and print ‘Hello Hojn King’ in the console.

In the next line, we have called the sayHello function passing the context of a person2 and Hi as a parameter. This will print ‘Hi Kelly Bail’ in the console.

The apply( ) method invokes a function with a given this value and parameters as an array.

In this example, we have called the sayHello function passing the context of a person1 and parameter Hello as an array. This will take the firstname and lastname from person1 object and print ‘Hello Hojn King’ in the console.

In the next line, we have called the sayHello function passing the context of a person2 andparameter Hi as an array. This will print ‘Hi Kelly Bail’ in the console.

The bind( ) method allows us to bind a function with a context. The function can then be called later on passing any number of parameters.

In this example, personContext1 variable binds the function with the context of person1. With the help of this personContext1, we can call the function by passing the required parameters, ‘Hello’ in our case.

Again personContext2 is created by binding the function with person2 object. In this way, we can make use of bind( ) method.

Subscribe to our youtube channel for more videos :

https://www.youtube.com/@codeymaze.

--

--

CodeyMaze
CodeyMaze

Written by CodeyMaze

Crafting Solutions Through Code & Words https://codeymaze.com Feel free to follow me :)

No responses yet