| « Better still | 2011: An open letter » |
Wed, Dec 28, 2011
![[Icon]](rsc/img/chain_link.gif)
I hate Javascript.
Mostly because of things that aren't really its fault, to be fair:
But when you look under the hood.. it's no better! Global variables, weird scoping (A helper function defined inside a method gets the global object bound to 'this' instead of the object bound to the method's 'this', FFS), godawful class syntax...
So when somebody at work recommended a book called "JavaScript: The Good Parts" my immediate reaction was "It must be a very short book! Ha! Ha!"
It is.
150 pages, and 50 of it's appendices. Only 100 pages could be written about what's good about JS.
The blurb on the back of the book? Well, it begins:
Most programming languages contain good and bad parts, but JavaScript has more than its share of the bad
This seemed promising.
And it is. It's a damn good book. It throws out all the cruft and the useless "Hello, world" nonsense that most JS books blither on about, and just tells you about what JS got right and how to use it properly.
Don't use the class syntax. JS isn't classical: It's prototypal. An object isn't an instance of a class; you make a new object by linking to the prototype of the type of object you want.
Don't think of it as anything to do with Java, don't think of it with your C hat on. It's more functional than procedural: Put your Lisp/Haskell/Higher Order Perl hat on. Don't think about global variables, think about data stored in closures.
And suddenly if you want, say, iterator objects, you don't have a bunch of global variables or bad class syntax. You can dump all of that and create objects with closures that you can pass around by reference. And it's almost like you're using a decent language again!
var Counter = function (start){
this.counter = typeof start == 'number' ? start : 0;
};
Counter.prototype.count = function (){
return this.counter++;
};
var count_zero = new Counter();
var count_hundred = new Counter(100);
var count_badly = new Counter('wibble');
As simple as that, you can now get the output:
- count_zero.count(); 0 - count_zero.count(); 1 - count_hundred.count(); 100 - count_hundred.count(); 101 - count_badly.count(); 0 - count_badly.count(); 1
All nice and sane. And, compared to what you usually see in JS, quite elegant.
If the rest of the book is as helpful as the first third, I live in hope that I may yet be able to add "Just use raw JS" to the existing list of "Use Jquery" and "Learn EXT" that I currently have available for making web pages dynamic.
![[Links]](http://geekblog.oneandoneis2.org/skins/112/rsc/img/chain_link.gif)
Hmm.. new look for twitter? I hope it gets less "Ick! Change! Put it back!" nonsense than Facebook..
08/02/12
Facebook Syndication Error
22/02/12
![]()
I last listened to:
Johann Pachelbel - Canon in D major
Most recent photo:
Submersible houseboat