BYOAWA Errata/Comments, Part 1

Posted by mde [ Fri, 30 Jun 2006 04:22:00 GMT ]

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 .