DEV Community

jcfrane
jcfrane

Posted on

call vs apply vs bind

If you started your career as a javascript developer using frameworks such as vue and angular, javascript native functions might be unfamiliar to you. If you stumbled upon functions like call, apply, and bind and seems you can’t wrap your head around them, this article is for you.

All these 3 methods allow you to change the this context of a function.

Suppose you have the following code:

function sayName() {
  console.log(this.name)
}

sayName()
Enter fullscreen mode Exit fullscreen mode

The output of this call is undefined. Because this refers to Window(if you are running the code in a browser) object and it has no name property. Thus, the undefined.

The call() method

call() basically calls a function with the given lexical context as parameter like so:

let human = { name: 'JC' }
function sayName() {
  console.log(this.name)
}

sayName.call(human); // Outputs JC
Enter fullscreen mode Exit fullscreen mode

Another thing you can do is to supply argument/s to the function like so:

let human = { name: 'JC' }
function sayName(greeting) {
  console.log(greeting + ' ' + this.name)
}
sayName.call(human, 'Hi!') // Outputs Hi! JC
Enter fullscreen mode Exit fullscreen mode

The apply() method

apply() is just like call() except that it accepts arguments in array like so:

let human = { name: JC }
function sayName(greeting, city) {
  console.log(greeting + ' ' + this.name + ' from ' + city)
}
sayName.apply(human, ['Hi', 'Taguig']) // Outputs Hi! JC from Taguig
Enter fullscreen mode Exit fullscreen mode

with call() you have to supply the arguments individually like so:

console.log(sayName.call(human, 'Hi!', 'Taguig')) // Outputs Hi! JC from Taguig
Enter fullscreen mode Exit fullscreen mode

The bind() method

The bind() is somewhat special. It is a higher-order function which means it returns another function when you invoke it. The function returned is curried, meaning you can call it multiple times to provide different arguments in each call. It is a complex topic you can read more about it on the internet. For now, let’s apply it on our example:

let human = { name: 'JC' }
function sayName(greeting, city) {
   console.log(greeting + ' ' +     this.name + ' from ' + city)
}

let greet = sayName.bind(human)
greet('Hi!', 'Taguig') // Outputs Hi! JC from Taguig
greet('Hello!', 'Makati') // Outputs Hello! JC from Makati
Enter fullscreen mode Exit fullscreen mode

That’s it! I hope I was able to demistified these 3 methods for you. Thanks for reading my article!

Originally posted at jcfrane.com

Top comments (0)