JavaScript objects and Crockford's The Good Parts
- by Jonathan
I've been thinking quite a bit about how to do OOP in JS, especially when it comes to encapsulation and inheritance, recently.
According to Crockford, classical is harmful because of new(), and both prototypal and classical are limited because their use of constructor.prototype means you can't use closures for encapsulation.
Recently, I've considered the following couple of points about encapsulation:
Encapsulation kills performance. It makes you add functions to EACH member object rather than to the prototype, because each object's methods have different closures (each object has different private members).
Encapsulation forces the ugly "var that = this" workaround, to get private helper functions to have access to the instance they're attached to. Either that or make sure you call them with privateFunction.apply(this) everytime.
Are there workarounds for either of two issues I mentioned? if not, do you still consider encapsulation to be worth it?
Sidenote: The functional pattern Crockford describes doesn't even let you add public methods that only touch public members, since it completely forgoes the use of new() and constructor.prototype. Wouldn't a hybrid approach where you use classical inheritance and new(), but also call Super.apply(this, arguments) to initialize private members and privileged methods, be superior?