Javascript Fundamentals: bind() and currying

Lets use bind() in our game we used for call() and apply()


Allan Sendagi

2 years ago | 1 min read

We have seen how bind() is used to fix the dynamic nature of the this keyword at least before the introduction of arrow functions in ES6.

bind() unlike call() and apply() returns a new function with a certain context and parameters. It’s usually used when we want a function to be called later on with a certain type of context or a certain type of this keyword.

Lets use bind() in our game we used for call() and apply()

We could say Wizard.heal.bind(archer, 50, 30) but unlike call and apply, bind doesn’t run the function. It returns a function. So that if I add it to a variable, we can use this function, later on.

bind() just like call accepts parameters

We can now run healArcher().

So bind allows us to store the this keyword or our borrowed function for later use. It’s like a band-aide that fixes the dynamically scoped this keyword that ruins our entire scoping.

To summarise, call and apply are useful for borrowing methods from an object while bind helps us call functions later on with a certain context.

bind and currying

Currying refers to partially giving a function a parameter. In this case, we are doing multiply(2) vs multiply(2,5).

Now, why would this be useful?
Let's have a variable

this here refers to the window object and we don't really care about it here. What we care about is giving the parameter to the multiply function. this is just the unintended consequence of using bind.

But now if we give 2 our multiply function 2 and run it, it returns for us a function that we can use later on which already has one of the parameters in it.

So that if I run multiplyByTwo(8), I get 16.

I created a new function called multiplyByTwo that multiplies anything by two by giving it the first parameter to be 2.

We can change this to anything lets say 4.

So that

We were able to reuse a piece of code by giving it a partial parameter and we created these functions that are extensible such as multiplyByTwo() and multiplyByFour().


Created by

Allan Sendagi

Technology will save homo sapiens from extinction







Related Articles