Social Icons

twitterfacebookgoogle pluslinkedinrss feedemail

Sunday, July 26, 2009

How to create a namespaced JavaScript Object/Class

One of the most important things you can do when creating JavaScript Objects/Classes for reuse throughout your web application or website (or both) is to utilize a namespace that will ensure no pollution occurs when you start to use other JavaScript libraries and APIs. Just like C++ introduced the concept of namespaces and Java introduced the concept of packages, it's good to ensure your code is isolated enough so that it's guaranteed (well, mostly) to work the same no matter which libraries you wind up utilizing.

Creating JavaScript classes isn't hard. It's simply a matter of doing something akin to the following:

  function Foo(theBar) {
  
    this.bar = theBar;
  
    this.getBar = function() {
      return this.bar;
    }
  }
  
That's pretty much it. You can add additional methods as you see fit. You can now instantiate class Foo and execute getBar() as follows (note that I don't define what the bar parameter is, but it can be anything - here it is an integer):
    var f = new Foo(1);
    alert("bar is: " + f.getBar();
  

The problem with this is that anyone can add any method to your class by calling and executing:

    // add function
    Foo.prototype.bat = function() {
      alert("new function!");
    }
  
    // execute function
    var f = new Foo(1);
    f.bat();
  
This is kind of bad, yes? Namespacing your class makes it harder (and in one case as we'll see below, impossible) for people to do this effectively making your class "final" in that no methods can be added, polluting your class. So, how do we namespaceify our class? Simple. Change the above to the following:

  var Foo = function(theBar) {
  
    return {
  
      method1 : function(message) {
        alert(message);
      },
  
      method2: function(anotherMessage) {
        alert(anotherMessage);
      }
    };
  }();

Now, if someone tries the same 'Foo.prototype.bat = ...', they will get a JavaScript error saying prototype doesn't exist - because it doesn't.

One downside to this is that all the methods defined above are "static" meaning that they can be called via 'Foo.method1()' or 'Foo.method2().' We can add a constructor function to the namespace and while the "outer" class Foo is still immutable to prototype, we cannot prevent methods from being added to instances of the constructor function - however, using a namespace will better protect against namespace pollution. Here's the final example:

  var Foo = function(theBar) {
  
    var privateField;
  
    function privateFunction() {
      // contents
    }
  
    return {
  
      method1 : function(message) {
        alert(message);
      },
  
      method2: function(anotherMessage) {
        alert(anotherMessage);
      },
  
      // a "constructor" function
      aClass: function(theFoo, theBar) {
  
        this.foo = theFoo;
        this.bar = theBar;
  
        this.getFoo = function() {
          return this.foo;
        }
  
        this.getBar = function() {
          return this.bar;
        }
      }
    };
  }();
  
Notice that we've added a private field and private methods as well as a constructor function with private fields and member methods.

Friday, July 10, 2009

Post Season Drama

Ok, so there's really no drama here. I'm done for the season but that doesn't mean I'm going to let myself go. I still workout at least 4 days a week. It would be nice to get into some type of pattern, but then, that would kind of imply training and I'm definitely not doing that.

So, if I feel like running, I'm going to go for a run. If I feel like swimming, I'll go to Master's swim, and if I feel like riding, I'll ride my road or mountain bike because I'm not touching my tri bike unless absofuckinglutely necessary.

More Post-Race Musings

Upon some more reflection, I've learned that during an Ironman it's best to be very flexible as one never knows just how one's body will respond to what it's being subjected.

I've also learned that while I wouldn't recommend it for training, chocolate chip cookies and pretzels make an excellent race food at mile 15 on the run of an Ironman.

In the Era of the Cell Phone

I left my keys at work today and I didn't realize it until I was looking in my bag for my wallet and keys about to get off the bus some 30 minutes after I left a locked office for the weekend. Within the next 40 minutes, however, I was at home, my keys were on their way home to me, and I didn't even have to walk home.

After I got off the bus, I called my wife some 10-15 times until I got a hold of her to inquire as to where she was. As she'd not yet left Denver, she was pretty much out for getting a ride home. I then called our friend Ashley who happened to have driven to work that day. After a quick explanation of my situation, she said she could swing by and pick me up on her own way home. I spoke with my wife again who offered to stop by the office and pick up my keys. The problem was that I needed someone in the office to let her in as it was locked and most everyone had already gone home. I wound up getting a hold of Randy, one of our sys admins and all around office god. He brought my keys down to my wife and the crisis was averted.

Now, take out the cell phone and what would have happened? Better yet, what if I weren't married or lived alone? I'd have had to go back to the office to get my keys.