Sergio and the sigil

Upcoming Local UG Meetings

Posted by Sergio on 2009-07-06

Here are two user group events that are happening soon and that I'm directly involved.

July 8th, Chicago ALT.NET

0-60 With Fluent NHibernate
See the full description of the session over at the Chicago ALT.NET home page. We will have Hudson Akridge tell us all about Fluent NHibernate, a project that has been instrumental in getting people on NHibernate by simplifying a lot of that ORM's configuration chores.

The Chicago ALT.NET meetings start at 6PM in the Sears Tower. Check the website for complete location details.

July 14th, WI.NET

JavaScript - Beyond the Curly Braces
I'm taking my little JS presentation to the WI.NET UG in Milwaukee. The group's website hasn't been updated with the presentation details yet but it's basically the same presentation given at other local UGs.

The meeting starts at 7PM. Come ready to be surprised.

UPDATE: The video and slides from this presentation have been published.

Spotlight on JavaScript at the CNUG

Posted by Sergio on 2009-06-15

This Wednesday, June 17th, the Chicago .NET Users Group, CNUG, has invited me to bring my JavaScript presentation to their monthly meeting.

Despite of what the event description might lead you to believe, the talk is hardcore JavaScript, not much specific to Ajax at all, although I believe the material will greatly help you with the Ajax work as well.

You can read the complete talk description and register for the event. Hope to see you there.

JavaScript: Not your father's inheritance model - Part 1

Posted by Sergio on 2009-06-12
This post is part of a series called JavaScript Demystified.

This particular chapter is further divided in two parts. Read Part 2.

In a previous installment in this series we saw how we could create constructor functions in JavaScript. Back then I just mentioned that we don't have classes in JavaScript and that there's this weird prototype property in every object.

Let's dig into those concepts a little more and try to understand how inheritance is achieved in JavaScript.

Inheritance as we often know it

For myself and probably the majority of you reading this blog, inheritance in an Object Oriented programming language is directly associated with the concept of classes.

When we work with C#, VB, Java, Ruby, and many other popular programming languages, each of our objects is of some type, which is represented by a class. Our objects automatically inherit functionality from their associated class often called base or super class, and any other classes that the base class itself is associated with (i.e. derives from.)

That's nothing new to you, I'm sure. I'm just re-hashing that in the previous paragraph to make a comparison later. Let's call this model class-based inheritance.

That's not the end of the story

This may come as a surprise to some people, but class-based inheritance is not the only way to obtain Object Oriented inheritance (by saying Object Oriented I automatically excluded those of you that thought Copy/Paste Inheritance was one of them.)

It just so happens that the JavaScript language designers chose another inheritance model. And they are not alone in that choice. By opting for a prototype-based inheritance model , JavaScript joined the ranks of other programming languages such as Self , Lua , and Agora.

The prototype is the king

Objects in JavaScript don't inherit from classes; they inherit straight from other objects. The object they inherit from is called their Prototype (I'm using a capital P here to avoid confusion down the line.) The object's Prototype is assigned right at construction time.

You may be intrigued and say: But when I create my objects I don't remember specifying any Prototype stuff. What gives?

Let's see what happens then. When you create a plain Object using either of the following syntaxes

var obj1 = new Object();
obj1.name = 'box'
//or
var obj2 = { name: 'door' };

JavaScript will automatically assign a Prototype to each of these objects. This prototype will be Object.prototype.

Similarly, let's see what happens with a few of the other object types in JavaScript.

The Prototype objects is how every object in JavaScript is born with inherited functionality. For example, the substring() method that every String object has is a method defined in the object String.Prototype.

The prototype objects themselves also inherit from Object.prototype, that's how every object of any type has a toString() method.

When you try to access 1234.constructor, as an example, the runtime will look for a constructor property on our object (the number 1234). It doesn't have one so the next step taken is to check if that object's Prototype has it. The Prototype for 1234 is Number.prototype and it doesn't have that property either. The runtime then looks on the Prototype of Number.prototype, which is Object.prototype. That last object does have a constructor property, so that is returned. If it didn't, undefined would have been returned instead.

In Part 2 we will see how to create our own Prototypes.

JavaScript: Not your father's inheritance model - Part 2

Posted by Sergio on 2009-06-12
This post is part of a series called JavaScript Demystified.

This particular chapter is further divided in two parts. Read Part 1.

Build your own hierarchy

Let's pretend we are building some scripts that deal with musical instruments. We could define our own Guitar class type like this:

//The constructor
function Guitar(brand, model) {
    this.brand = brand;
    this.model = model;
    this.strings = ['E', 'A', 'D', 'G', 'B', 'e'];
}

//Instance methods
Guitar.prototype = {
    play: function (chord) {
        alert('Playing ' + chord); 
    },
    toString: function () {
        return '(Guitar: ' + 
            this.brand + ' ' +
            this.model + ')';
    }
};

var guitar1 = new Guitar('Gibson', 'Les Paul');

What may not be apparent by just looking at the code for the first time is that guitar1's Prototype will be Guitar.prototype, which means that guitar1 inherits from Guitar.prototype. Also guitar1.constructor === Guitar.

When the last line in the above example is executed, the JavaScript runtime will take care of initializing a new object that has Guitar.prototype as its Prototype and makes its constructor property point to the Guitar function.

But what if we want to create a different type of guitars and still reuse the existing Guitar type. We could do this:

function BassGuitar(brand, model) {
    //call the constructor of our base type
    Guitar.apply(this, [brand, model] );
    //change or add anything we wish
    this.strings = ['E', 'A', 'D', 'G'];
}

//Copy the Prototype of our base type
BassGuitar.prototype = Object.create(Guitar.prototype);

//Override whatever we want:
BassGuitar.prototype.toString = function () {
    return '(BassGuitar: ' + 
        this.brand + ' ' +
        this.model + ')';
};

var bass1 = new BassGuitar('Peavey', 'Cirrus');
bass1.toString(); //=> '(BassGuitar: Peavey Cirrus)'
alert(bass1.strings); //=> [ 'E', 'A', 'D', 'G' ]

But there's a problem with the above code. There isn't a method Object.create(). Yeah, that's one of the design omissions in JavaScript. Any prototype-based language needs an easy way to let use create objects from other objects.

Thankfully JavaScript is also dynamically typed, so we can add that function ourselves. Here I'm borrowing from Douglas Crockford.

//add this to the very beginning of your scripts
if (typeof Object.create !== 'function') {
    Object.create = function (o) {
        function F() {}
        F.prototype = o;
        return new F();
    };
}

I'll leave the interpretation of the above function as an exercise to the reader. Once you understand what it is doing you will have mastered prototypes and constructors.

Handy Prototype tricks

Knowing what we know now and once again leveraging JavaScript's dynamism we can fix one of the things that has always annoyed me in JavaScript: the lack of a trim() method on strings.

String.prototype.trim = function () {
    return this.replace( /^\s*(\S*(\s+\S+)*)\s*$/, "$1"); 
}; 
var text = ' some user-entered value   ';
alert( text.trim() ); // => 'some user-entered value'

How about an easy way to pad numbers with zeroes?

Number.prototype.padLeft = function (width) {
    var text = this.toString();
    for(; text.length < width; ){
        text = '0' + text;
    }
    return text;
};

var num = 1234;
alert(num.padLeft(6)); // => 001234

Why do I need to know all this stuff?

Well, you don't. But why even bother writing JavaScript code if you're not willing to learn how it works?

As we have been seeing during this series, JavaScript bears only some syntax similarities with C# or Java. Underneath the surface it has been designed very differently. The web is riddled with attempts to mimic class-based inheritance in JavaScript only because programmers don't want to learn and leverage prototype-based logic.

My humble advice is that you will feel happier and smarter if you chose to learn how to use the language as it was intended.

The Chicago Code Camp has got you covered

Posted by Sergio on 2009-05-19

As a brief inspection of your RSS reader will quickly tell you, it's Code Camp season. Not to be left out of this party, the developers in the Chicago and Milwaukee areas have a great option this year.

The Chicago Code Camp, which happens on May 30th, is strategically located right between these two cities.

The agenda has been published and it's pretty exciting to see so many interesting and useful topics in a single event.

.NET still dominates the schedule but there's a lot of options for developers of virtually all walks of life. Here's a quick summary (we will have 33 sessions but some cover more than one topic)

  • .NET: 20 sessions
  • Ruby: 6 sessions
  • TDD: 6 sessions
  • JavaScript: 3 sessions
  • Functional Programming: 3 sessions
  • Cloud computing: 3 sessions
  • Python: 2 sessions
  • Java: 2 sessions

The bad part is that we can't be at all the sessions we'd like — there will be 5 or 6 concurrent talks. Here are some sessions that interest me in particular:

Those are only a few of the talks. I'm sure you'll be able to find sessions of your own interest. RSVP below. Hope to see you there.

RSVP