Javascript: is this a code smell?
I’ve been bringing myself up to speed in modern Javascript, which is (a) a serious programming language, capable of supporting substantial work, and also (b) a never-never land of great strangeness.
The two faces are not unrelated. The language wasn’t meant to do great things or even to be a serious language. It was not very carefully designed, and was standardized too soon. It was not destined for greatness, but it had greatness thrust upon it, and Crockford showed that it was in fact capable of doing what needs to be done. Because it’s ubiquitous, lots of effort is going into making Javascript fast. Like it or not, it’s going to be an important language for all kinds of work.
But, let’s face it: any language where, when you say "I want to define a new class", you begin by calling an anonymous function: var myClass=function(){ return {}; }()
— well, this is going to frighten the children.
My current puzzle is this.
A code smell is a pattern that experienced programmers recognize as a suggestion that something is mildly amiss. For example, suppose I have an object ShopFloor which has a method:
Product *thing=...
thing->Mill();
thing->Drill();
thing->Fill();
thing->Polish();
thing->Pack();
This suggests immediately that our procedure should not be a method of ShopFloor at all. We want all these things to be a method on Product:
Product::Make() {
Mill();
Drill();
Fill()
Polish();
Pack(); }
The product knows how it’s made. All those repeated pointers to thing are telling you that the method belongs on another object.
Now, Crockford-style Javascript, it seems to me, says “this” and awful lot. You can get around this with private variables, but I'm finding private variables get pretty awkward in larger objects. You quickly wind up with several pages of code inside the original class definition, with all sorts of nested definitions. That itself is a code smell! (I find myself counting braces in a old LISP style when I do this, and surely that can’t be a good thing.)
Should I reconcile myself to using this a lot? Should I tell myself, “It’s just JavaScript,” and ignore the aroma? Am I missing an idiom? It feels terribly artificial to me, but then again, I remember when various Smalltalk and LISP and (especially) C++ idioms seemed pretty bizarre.
For that matter, I’m surprised I’ve not seen more discussion of these questions. There are plenty of bad beginner’s texts, and there’s Crockford, and I’ve found a bit of useful discussion here and there. One problem is that some very bad and old Javascript sites have lots of Google Juice, which makes life harder, while forum advice at places like StackOverflow veers uncannily from expertise to the ravings of misinformed children. From the outside, it’s sometimes hard to know who is who.