BYOAWA Errata/Comments, Part 1
2006-06-30 02:22:00
I kind of like how the acronym for the title of my book starts with 'BYO' -- kind of makes it sound like you might start doing keg stands a few chapters into it.
It's only been out a week, and there's already something I'm noticing in code I'm writing now that would have made for cleaner example code in the book.
Because of how JavaScript uses lexical scope, a lot of the places I used the local variable self
multiple times as an alias for 'the current object' (coding around the loss-of-scope annoyance you get with XHR, setTimeout
, and friends), I could have just used a single 'private member' self
inside the constructor function.
In the book I generally tried to take the easiest approach with the loss-of-scope stuff, so I made heavy use of the Singleton pattern in the example code. So, there's a lot of code that looks like this:
var FlashGordon = new function() {
this.attack = false;
this.rocketCycle = 'ride';
function rideRocketCycle() {
var self = FlashGordon;
if (self.rocketCycle == 'ride') {
// Do rocket-cycle-riding stuff
}
}
this.attackMing = function() {
var self = FlashGordon;
self.attack = true;
// Do stuff to attack Ming the Merciless
}
this.saveUniverse = function() {
var self = FlashGordon;
if (self.attack) {
// Do stuff to save the universe
}
}
}
That could be made a bit less verbose like this:
var FlashGordon = new function() {
var self = this;
this.attack = false;
this.rocketCycle = 'ride';
this.save = false;
function rideRocketCycle() {
if (self.rocketCycle == 'ride') {
// Do rocket-cycle-riding stuff
}
}
this.attackMing = function() {
self.attack = true;
// Do stuff to attack Ming the Merciless
}
this.saveUniverse = function() {
if (self.attack) {
// Do stuff to save the universe
}
}
}
Note that it's also a handy way to give your private methods access to the object as well. I would have noticed this earlier if I'd paid better attention to Professor Crockford.
Comments
new function()
makes it an anonymous 'one shot' constructor. (The error you'd get with your code is "FlashGordon is not a constructor.") However, since I was lazy and didn't nail down the constructor
method that every object has, you could actually create a new FlashGordon by doing var newFlash = new FlashGordon.constructor()
. To keep people from using that little loophole, I should have done FlashGordon.constructor = null
.