Javascript Bind function1 min read

Javascript Bind! What,when and how?

Bind is a functional Javascript thing, which means it’s used in various frameworks like Angular, React, Vue etc.

The PROBLEM!

Assume we have a animal shelter with a dog and cat.

this.animal = "Dog";

 var animalShelter= {
     animal: "Cat",
     getAnimal: function() {
         return this.animal;
     }
};


console.log(animalShelter.getAnimal()); // outputs "Cat"

If we want to store getAnimal function for later use, we would do something like this:

var notWorkingAnimalFunc = animalShelter.getAnimal;

Now if we use the stored function:

console.log(notWorkingAnimalFunc()); // outputs "Dog"

As you can see, you will probably go WTF!?!?! Just as i did once! 😀
Most common scenario where this could be a problem is when using promises.

WHY?

What Javascript does is, switches this from getAnimal function to top (outer function) this.

this.animal = "Dog";

 var animalShelter = {
     animal: "Cat",
     getAnimal: function() {
         return this.animal;
     }
};

HOW?

So… how do we use / bind animalShelter.getAnimal function to workingAnimalFunc? Easy:

var workingAnimalFunc = animalShelter.getAnimal.bind(animalShelter);

console.log(workingAnimalFunc()); // outputs "Cat"

What we do here is we bind getAnimal function to object animalShelter. This way function workingAnimalFunc knows it will use this, which is scoped to that particular object (animalShelter).

SUMMARY:

  • It’s a Javascript prototype
  • We use bind when we want to scope this to a context of a particular object / function.

Leave a Reply

Your email address will not be published. Required fields are marked *