DEV Community

Ronnie
Ronnie

Posted on • Edited on

2 2

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

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(){
  console.log(this.snack)
} 

eat();
// will return undefined
Enter fullscreen mode Exit fullscreen mode

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

let boundEat = eat.bind(meal)

boundEat();
// 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!

Image of Bright Data

Ensure Data Quality Across Sources – Manage and normalize data effortlessly.

Maintain high-quality, consistent data across multiple sources with our efficient data management tools.

Manage Data

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay