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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With