Using The .apply.bind() Combo in Javascript

Context in Javascript is a powerful concept that is very particular to the language, and is usually determined by how a function is invoked. Being able to control it can open the spectrum for very interesting patterns. One way you can achieve context manipulation is by using the .bind() method, which allows us to create a new function with a new context (or ‘this’). Another way of changing the context is by using the .apply() method. This one rather than returning a function, it calls the function with a different context passed as a first argument, and an array as the second.

To make this more interesting, I want to create a function that combines the features of both methods. To achieve this, we can call .bind() on top of apply, resulting in a function which is basically .apply() with its first argument fixed to whatever we want to. In this case


So now we have both functionalities mixed into one function. The context being applied and the ability to pass an array that will get deconstructed into separate arguments. Let’s look at a bit more elaborated example now.

Simulating a cake maker

To play a bit more with the apply.bind combo, we’re gonna create a factory that generates methods to simulate a basic process of baking cakes. First we’re gonna define a list of base ingredients that we’ll be re-using each time we want to bake a cake, so we don’t have to add them every time. For the list of common ingredients, we’ll define an object that contains an array that will be shared among all generated objects. The key here will be to inject the list of ingredients as context to the cakeMaker function. So each time we create a new cake, that list of base ingredients will always be available by default.

We’ll now define the main function that holds all the necessary methods to execute each part of the baking process.

Next up, via the same methodology of the last example, the function will get that list of common attributes injected via the ‘apply.bind’ to make them available across any generated function as part of their context.

With the created generator, we can now create different types of cakes based on a set of initial preferences and additional ingredients.