Free AI web copilot to create summaries, insights and extended knowledge, download it at here
1438
Abstract
/205e6c763f187fd53a188e8f0f8cd391.js" allowfullscreen="" frameborder="0" height="undefined" width="undefined">
</div>
</div>
</figure></iframe></div></div></figure><p id="e12c">Given the OOP nature of the builder pattern, you may think that to implement it you have to use classes. But I am here to prove you wrong: this pattern is perfectly valid for functional languages such as JavaScript, thanks to the prototypical delegation and <code>this</code> binding.</p><figure id="fbf7"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/0*8IhFCwkSROOD_s6r.jpg"><figcaption></figcaption></figure><h1 id="c177">Implementing the builder pattern in JavaScript</h1><p id="89b7">To implement the builder pattern, we are going to use the constructor functions, the <code>new</code> keyword and <code>this</code> binding. Note that these features have nothing to do with classes, their behavior is not related to classes and they were introduced way before classes were. As a use-case for the builder pattern, imagine that you have to perform a lot of common HTTP requests to the same server with the same header and would like to simplify the API. Observe this code:</p>
<figure id="636b">
<div>
<div>
<iframe class="gist-iframe" src="/gist/r3dm1ke/8a20067238bf0900af65e5938591e1a7.js" allowfullscreen="" frameborder="0" height="undef
Options
ined" width="undefined">
</div>
</div>
</figure></iframe></div></div></figure><p id="dba3">First, note the ClientBuilder function. It returns an object that holds all the building logic. It exposes functions <code>forBaseUrl</code>, <code>withHeaders</code>, <code>usingFetch</code>, <code>usingAxios</code>, and, <code>build</code>. You use these functions to specify the desired behaviour and then use <code>build</code> to get the complete client. The <code>Client</code> function is a constructor function, that accepts <code>baseUrl</code>, <code>headers</code> and <code>executor</code>, binds it via this and exposes functions <code>post</code> and <code>get</code>. You will then use these functions like this:</p>
<figure id="c71b">
<div>
<div>
<iframe class="gist-iframe" src="/gist/r3dm1ke/e76da0bf65fcf601e403c27ec5da19cb.js" allowfullscreen="" frameborder="0" height="undefined" width="undefined">
</div>
</div>
</figure></iframe></div></div></figure><p id="a695">This wraps up our discussion about the builder pattern in JavaScript, hope you found it useful. Let me know what other design patterns you want me to cover!</p><figure id="9f62"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*zWeFS3E1gbkEuBmpbvm6Rg.jpeg"><figcaption></figcaption></figure></article></body>