Denis Jakus

Demystifying Tech & Management

CTO x Unique People

AI / ML / ChatGPT

Unreal Engine

Low Code

Management & Leadership

IT Consultant

Denis Jakus

Demystifying Tech & Management

CTO x Unique People

AI / ML / ChatGPT

Unreal Engine

Low Code

Management & Leadership

IT Consultant

CTO Note

Javascript Bind function1 min read

24 September 2017 Javascript
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.
Taggs:
Related Posts
Learn how to use async inside useEffect hook

Facebook Twitter Evernote Hacker News Gmail Print Friendly Yahoo Mail reddit LinkedIn Blogger Tumblr Like Did you stumble upon a…

Javascript Splice VS Javascript Slice

Facebook Twitter Evernote Hacker News Gmail Print Friendly Yahoo Mail reddit LinkedIn Blogger Tumblr Like Little chit-chat Hi! Let me…

Write a comment