Abstract Composition Because everyone has to have a blog, right?

Javascript Functions Holding Their Own Data

In Javascript functions are objects, a fact most of us overlook. They are special callable objects but still just objects. Because of this, functions have properties. For example MyFunction.name will return the name of the function. Recently I was reading the excellent JavaScript Patterns book which reiterated this fact about functions but this time I suddenly had a light bulb moment. I started thinking about use cases where this could be useful and the concept became fascinating. Just imagine it, functions that hold their own state! Functions that cache their calculations within themselves! No more external variables to hold data that is tightly coupled to the function. What a cool idea! This, of course, is not a new idea it’s the concept of Memoization.

Example 1

You have an initialization function that you want to ensure only runs once.

function Init()

    // Do stuff

    Init.initialized = true;

Example 2

Let’s say you have a function that builds and returns an HTML element. After building the element you could cache a reference to it locally in the function. This keeps the function self contained and efficient since it’s not using any external variables and it only builds the element once.

function GetWidgetElement()
      return GetWidgetElement.element;

    var div = document.createElement("div");
    div.className = "myWidget";

    return GetWidgetElement.element = div;


Of course just because we can store data in functions doesn’t mean we necessarily should. I’m sure a good argument could be made that it’s bad programming practice. That it makes the code less understandable. Most people might get quite confused if they don’t know functions are objects with properties. This technique could most definitely be abused. The properties are still public to anyone that has access to the function so you aren’t shoving it into a secret hiding space.

When introduced carefully I think this trick could be used to fantastic effect. Creating functions that rely less on external variables to hold state/data when it’s only relevant to that function sounds like a good idea to me.