JavaScript inheritance and protected methods
I really like JavaScript, but it’s far from perfect. One of it’s imperfections is that you’ll have to resort to trickery to create private variables (iife). So what aboutinheritance and protected variables?
Lately I needed a base object to inherit multiple objects from. JavaScript does not really have classical inheritance so I always use prototypal inheritance (also, I don’t like this). But I might reconsider with es6 classes, even though it’s just sugarcoated prototypal.
Protect your privates
So… prototypal inheritance. We can fake private variables and methods through closures, but this will also prevent us from accessing them in child objects. So what we’re really looking for are protected variables and methods. There’s no such thing in JavaScript of course (no, not even in es6).
But we can fake that to.
The solution I came up with for my project is really an abstract base object. And it’s not really a base object but more a singleton factory. It does have a lot of bind, but it works. Enough talk, here’s some code:
In the child object, instead of returning the instance, we return an instance property ‘expose’. This keeps the instance safely within the closure, effectively creating the illusion of protected variables and methods. There are limitations to this. The base object is abstract and the child objects are always final. Then again, you should never want to inherit too deep anyways.
And yes, it’s just a trick by convention, but it beats the hell out of prepending stuff with an underscore.
ps: here’s a fiddle