javascriptclosuresapplication-design

Is this a valid use case for javascript closure?


I have looked through all the other (excellent) answers on SO (especially this: How do JavaScript closures work?) but I wanted your feedback on my understanding of the concept.

I understand that one use case is to hide the implementation of private methods from public access.

The other one that I think of is having it as a factory generator:

<script>

function carFactory( make ) {
    return {
        manufacture: function ( model ) {
            console.log("A " + make + " " + model + " has been created");
        }
    }
}

toyotaFactory = carFactory("toyota");
hondaFactory = carFactory("honda");

toyotaFactory.manufacture("corolla");
toyotaFactory.manufacture("corolla");
hondaFactory.manufacture("civic");

</script>

This outputs:

A toyota corolla has been create
A toyota corolla has been created
A honda civic has been created 

So do you think its a valid use case for closures (i.e. creating multiple factories using the same code base)? Or can I achieve the same thing using something much better?

Please note that the question is less about the technical implementation of closures and more about valid use cases in application design / development.

Thanks.


Solution

  • Yes, keeping variables private is a valid use for a closure. It allows you to have private access to a variable without making it a public member.

    See this reference for other examples: http://www.crockford.com/javascript/private.html