Love the language, or hate it – I don’t think it’s debatable that its mechanisms for defining abstract data types are a bit… incoherent. This isn’t necessarily anyone’s fault; we know that the core of the language was bung out under duress and time pressure. But what we have to work with is a mishmash of dictionary types, an unfinished prototype system, a little bit of a Smalltalk/Java class system, and this behavior that not even a mother could love.
When I’m writing large amounts of code to run in the browser, I tend to approach the problem with higher level tools – GWT, JSX, TypeScript, Dart, Closure, and so forth. I personally find that I need a type checker to manage large projects (especially with a team), and at certain scales an optimizing compiler becomes indispensible. And for very simple scripts, simple Javascript with just dictionaries and functions is perfectly serviceable. But what about those occasions where you either can’t use a compiler (e.g., because you’re writing code for someone who doesn’t want to integrate it into their build system), or it’s too painful to be worth the effort (e.g., medium-sized Chrome extensions)?
When I find myself in this situation, I fall back to a pattern that I find takes a lot of the pain out of raw Javascript. I feel it gives me just the right set of abstractions to keep the code from turning into a creeping spaghetti monster, without much boilerplate, and that eliminates a few very difficult-to-avoid Javascript errors. The following is a simple, contrived example that should get the rough idea across. You may note that it derives to a certain extent from what’s come to be known as the Crockford Pattern, though I’ve extended it a bit.
Your new post is loading...