Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ) {

    var m = make;
    return { manufacture: function ( model ) 

        {console.log("A " + m + " " + 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.

like image 859
Software Guy Avatar asked Jul 16 '12 00:07

Software Guy


2 Answers

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

like image 188
jfriend00 Avatar answered Sep 16 '22 21:09

jfriend00


If I'm understanding your question correctly, you aren't concerned with keeping the make property private? If that's the case, then a closure isn't really necessary, and you could achieve the same functionality using a prototype...

function carFactory(model){
  this.m = make;
}

carFactory.prototype.manufacture = function(model){
  console.log('A ' + this.m + ' ' + model + ' has been created');
}

Which has associated performance benefits (reduced memory and increased speed), as per this question.

like image 26
market Avatar answered Sep 17 '22 21:09

market