I know that a consequence of using the prototype is that all added properties and methods will be public. This is not really too much of a problem since I’m using a naming convention to distinguish between the internals vs. the public interface. So yes, everything is still technically public.
Would it be best to just add all methods and properties to the prototype — even ones that are intended to be internal — opposed to only adding public methods/properties to the prototype and dynamically creating the internal properties inside the constructor using this.property = value.?
It seems that since everything is going to be public anyway, we might as well add internal properties to the prototype as well.
I know about using closures to create private scope. My question is not about how to create truly private properties (which would mean ditching the prototype as any of those methods would not have internal access privileges), but about best practice when using the prototype.
function MyObjectA() {
this.myInternalProp_ = 5;
// ...
}
MyObjectA.prototype.myPublicProp = "Hello";
vs.
function MyObjectA() {
// ...
}
MyObjectA.prototype.myPublicProp = "Hello";
MyObjectA.prototype.myInternalProp_ = 5;
Placing properties on the prototype means that the properties are not only public, but shared. This becomes a problem when your property is a mutable type, such as a
Date:See also Using "prototype" for variables