OO advanced options in JavaScript – part V

In the last posts, I’ve been bashing on JavaScript’s support for emulating classical OO paradigms. As you can see, I don’t really think that that approach matches JavaScript’s dynamic and prototypal nature. In my opinion, you should only rely on JS’ prototypal nature for extending objects instead of thinking in terms of classes. I think that a simple example will explain this better. Once again, this is based on Crockford’s excellent online resources. Let’s start with a simple person literal object:

var person = {
    name: "luis",
    printName: function() {
        alert( this.name );
    }
}

Now, let’s suppose I want to create a new object (student) which expands the existing person object. The idea is to create a new simple type by introducing a new function and expand it by using changing its default prototype object:

var student = function(base) {
    var aux = function() { };
    aux.prototype = base;
    return aux;
}
student.age = 30; //new props
student.printAge = function() {
    alert(this.age);
}

Really simple, right?  Notice that in this example we’re not concentrating on creating classes; we’re simply creating objects and using the prototype property to expand an existing object with new properties. If you want to reuse this approach, you’ll probably want to rely Crockford’s helper:

if (typeof Object.create !== ''function'') {
    Object.create = function(o) {
        function F() { }
        F.prototype = o;
        return new F();
    };
}

And here’s how you’d use it:

var student = Object.create(person);
student.age = 30;
student.printAge = function() {
    alert(this.age);
}

And I guess this concludes my posts on writing OO code in JavaScript. I still have a couple of posts on this topic (JavaScript), so stay tuned for more!

Advertisements

~ by Luis Abreu on September 8, 2009.

One Response to “OO advanced options in JavaScript – part V”

  1. very cool & good info for beginners, thank you very much for sharing.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: