As far as I understand,Prototypal inheritance and closure are two incompatible ways for creating objects.
- With prototypes, all the instances share the same function
- With closures, each instance has its own function (with its specific closure)
By creating object using clojure, I am referring to the following pattern:
function createPerson(p){
return {
getName: function() { return p;}
};
}
When in writing a Javascript application, prototype is a better choice than closure for creating objects? I am not looking for general explanations about the advantages of prototypal inheritance. Instead, I would like to see a real-life web development scenario where prototype inheritance is really useful.
The only useful case I can think about is for augmenting basic types.
In your new example you don’t “create a person”. Instead, you return a plain js object.
Again, is not about closure versus protytpe, because I can also have:
That doesn’t take advantages of a closure, but use the same approach to create an instance of an object. As you see, using
closureagain has nothing to do with object creation, can be used – or not – together, despite if you use prototype or not:I generally avoid that, but you can have it. Also:
So, if your question is “why I should create an object in this way instead of a plain object” – that has nothing to do with closures – the answer is “because then you take advantage of the inheritance”: