Published on

Easy Understand of call, apply & bind Method In Javascript

Authors
  • Name
    Twitter

Call Apply Bind function

Img Credit : @jstrippa

This methods are very commonly use in JavaScript. Before jump into this tutorial, you must have the knowledge of this keyword, otherwise it will not work for you.

Lets get some idea with Example.

call()

First thing first , call method takes object as a first parameter, and others parameter are function arguments. Let’s see an example.

let Student = {
  name: 'Md Rathik',
}
let getStudentInfo = function (roll, depertment) {
  return `Welcome ${this.name}, Your roll number is ${roll}, section ${depertment}`
}
console.log(getStudentInfo.call(Student, 99, 'CSE'))
//Welcome Md Rathik, Your roll number is 99, section CSE

Here we have a Object Student and a function which takes two argument roll & department. So when call the function with call method, we gave first parameter as Object & others are function parameter.

apply()

call() & apply() both are almost same but there has one major difference. Besides both function invoke immediately.

apply() takes arguments as array.

Lets run this example :

let Student = {
  name: 'Md Rathik',
}
let getStudentInfo = function (roll, depertment) {
  return `Welcome ${this.name}, Your roll number is ${roll}, section ${depertment}`
}
console.log(getStudentInfo.apply(Student, [99, 'CSE']))
//Welcome Md Rathik, Your roll number is 99, section CSE

Hope you already got the expected output as call().

bind()

The main things to remember bind() function does not invoke the function immediately. its just return a function definition & we are able to use where we want.

let Student = {
  name: 'Md Rathik',
}
let getStudentInfo = function (roll, depertment) {
  return `Welcome ${this.name}, Your roll number is ${roll}, section ${depertment}`
}

let getStudentInfoBind = getStudentInfo.bind(Student)
console.log(getStudentInfoBind(99, 'CSE'))

when we bind getStudentInfoBind =getStudentInfo.bind(Student); its doesn’t invoke the function immediately. We had to call the getStudentInfoBind as function with parameters.