Sep 08

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( );

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() {

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() {

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!

1 comment so far

  1. Javascript Multi Level Drop Down Menu
    12:28 am - 9-9-2009

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