DEV Community


bind(), apply() and call() me maybe: Pt. 1

arynnboniface profile image Ronnie Updated on ・2 min read

This is part one of a three part series on JavaScript's bind(), apply() and call(). These three methods are pretty closely related, but I think that each one deserves its own post! These concepts can be a little difficult to grasp, at least they were for me, so focusing on one at a time will be helpful!

The this keyword:

  • This tutorial covers just about everything you need to know about this.

First, let's take a look at the docs on bind() from JavaScript MDN:

The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.
Enter fullscreen mode Exit fullscreen mode

That explanation is a little rough, especially if you're new to JavaScript. Let's break it down!

  • bind() returns a new function that has a specific value of this bound to it when invoked.
  • The parameter passed into bind() will become this.
  • You can add extra parameters to bind() after this initial this.
  • Use bind() when you want to call a function later on and with a specific context.

Here's an example without bind():

let meal = {
  snack: "apple"

let eat = function(){

// will return undefined
Enter fullscreen mode Exit fullscreen mode

Here is where bind() comes in to save the day!

let boundEat = eat.bind(meal)

// returns "apple"
Enter fullscreen mode Exit fullscreen mode

Now, let's see how we can add in those extra arguments!

let meal = {
  type: "dinner",
  consistsOf: "spaghetti and meatballs"
  chef: function(name) {
    return `Chef ${name} says: "We're having 
    ${this.consistsOf} for ${this.meal}."`

let chefSays = meal.chef.bind(meal, "Remy")

// returns Chef Remy says: "We're having spaghetti and meatballs for dinner."
Enter fullscreen mode Exit fullscreen mode

That's bind() simplified!

Discussion (0)

Editor guide