At our company we have pretty large body of PrototypeJS based JavaScript code, which we are porting to jQuery for several reasons (not really important here). I'm trying to set up coding guidelines to make/keep things tidy during the porting.
One observation from wading through the prototype based implementation is that a lot of code is written in OOP style (using Prototype's Class.create
), but the code is not "object oriented" in spirit. The general pattern I've seen: one "constructor" which you are expected to call (but not call twice, because the constructor uses hardcoded DOM id's), a bunch of other "functions" and event handlers, which you are not expected to call (but the because there is no "private" in JavaScript, you don't know that) and data sharing between all these functions through this
. Seen from the caller's point of view there is just one "callable" and nothing else.
I'm starting to believe that OOP in JavaScript can and maybe should be avoided in a lot of cases. At least for our use case, which is not the next generation Goole Wave UI, but simply put: a bit of AJAX based enhancements, registering some event handlers here and there, minor DOM manipulations and such.
- the functionality we need seems to be implementable just fine in the typical jQuery non-OOP way, using closure magic to obtain encapsulation and privateness. As side effect, the minification efficiency of the ported code is much better.
- OOP in JavaScript is non-traditional and confusing if you are coming from a "traditional" background. There are a lot of attempts and frameworks to approximate traditional OOP, but IMHO this makes things even more confusing and fragile.
- One thing that Crockford's "JavaScript the good parts" taught me, is that the true power of Javascript lies in function scopes and closures, much less in OOP patterns.
I'm wondering if there is wider support for this feeling that OOP in JavaScript doesn't really cut it as the sacred mantra, like it is in other languages/platforms. And, in extension, what kind of non-OOP/closure based patterns are much more preferable.
function
) is sufficient.