I know it's possible to mimic private variables in JS:
function ConstructorPattern() {
var privateVar = 'hi there';
this.getVar = function() {
return privateVar;
};
};
But according to Learning JavaScript Design Patterns when referring to some similar code with class Car
and method toString
:
The above is a simple version of the constructor pattern but it does suffer from some problems. One is that it makes inheritance difficult and the other is that functions such as toString() are redefined for each of the new objects created using the Car constructor. This isn't very optimal as the function should ideally be shared between all of the instances of the Car type.
So the solution given in my case would be to add the getVar function via the prototype:
ConstructorPattern.prototype.getVar = function() {
return privateVar;
};
But of course that function has no idea what privateVar
is so it doesn't work. I am aware of the module pattern but I specifically want to be able to instantiate multiple instances.
Is there any way to use the constructor pattern "properly" with prototypes while still getting "private" functionality?
EDIT: If there isn't a way to accomplish this, is it really that bad for methods to be redefined for each class instance? I've recently started working on a code base that takes this approach. It seems like the only thing I'm missing out on is inheritance?
EDIT2: Marking as a duplicate based on link from the accepted answer.