Javascript function pattern

Rick Marshall
Dec 15, 2017 · 1 min read

We all know the problem lots of javascript functions and a polluted global namespace. To manage this I have built a pattern for anonymous functions as variables to use client side in an application.

The basic requirement is that it is easy to stack the functions for initialisation calls and the functions within this function are effectively namespace protected from each other.

I am assuming you are familiar with the basic use of an anonymous function as the value of a variable:

var functionName = (() => { }) ();

To this we add some initialisation management:

var functionName = (() => {
let initDone = false;
let loadPrevious;
let init = () = {
if (!initDone) {
initDone = true;

if (functionName.loadPrevious) functionName.loadPrevious();
}}

Add a return to the function to expose internal variables:

return {init: init, loadPrevious:loadPrevious)

And after the function definition:

functionName.loadPrevious = window.onload; window.onload = functionName.init;

Replace the … with anything that needs to be done to initialise. Any asynchronous calls should have a callback function. You can sort of get some callback hell from this but there are ways to manage that (not the subject of this). Calling loadPrevious should be inside a callback function if you have async calls.

Of course other functions can be defined (as variables to avoid hoisting) within the function and exposed using the return value.

This simple and effective pattern has allowed us to build an extensive managed functional programming environment.

Rick Marshall

Written by

Founder Zenucom Pty Ltd. Inventor Unibase language — full stack SaaS tool. Designer, developer of applications. Programmer, data modeler, distributed systems.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade