JavaScript objects and Crockford's The Good Parts

Posted by Jonathan on Programmers See other posts from Programmers or by Jonathan
Published on 2012-11-01T11:25:45Z Indexed on 2012/11/01 17:16 UTC
Read the original article Hit count: 423

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:

  1. 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).

  2. 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?

© Programmers or respective owner

Related posts about JavaScript

Related posts about inheritance