OO advanced options in JavaScript – part IV

Published Mon, Sep 7 2009 20:34

Today we’ll wrap up the posts on JavaScript’s support for classical OO by showing how you can emulate multiple inheritance. The technique I’ll be showing here is based on Douglas Crockford’s excellent post on this topic. Ok, so suppose you’ve got two base classes which look like this:

var Person = function(name) {
    this.name = name;
}
Person.prototype.printName = function() {
    alert(this.name);
}
var Student = function(school) {    
    this.school = school;
}
Student.prototype.printSchool = function() {
    alert(this.school);
}

Now, let’s say that we need to create a new “type” which inherits from Person and Student (this example doesn’t really respect true OO principles, but stay with me just for the sake of the example, ok?). If you look at the existing “types”, you can see that the can easily reuse the printName and printSchool methods in our new “class”. We can even introduce a helper function that will copy only the necessary properties from each base’s prototype object:

Function.prototype.swiss = function(baseType) {
    for (var i = 1; i < arguments.length; i++) {
        var propName = arguments[i];
        this.prototype[propName] = baseType.prototype[propName];
    }
    return this;
}

The swiss method expects a base type (ie, a reference to an existing constructor function) and a list of properties that should be copied from the base prototype object. Returning this from the swiss method is a commodity: we can call it several times in order to “reuse” the necessary base methods. Here’s an example that shows how to use it:

var User = function(name, school) {
    this.name = name;
    this.school = school;
}
User.swiss(Person, "printName")
    .swiss(Student, "printSchool");
var newUser = new User("luis", "any");
newUser.printName();
newUser.printSchool();

You’ll probably be thinking that this isn’t really multiple inheritance. And I guess you’re correct, but this is as far as I’ll go to make it work. Notice that there are other approaches out there (just run a search for multiple inheritance on google and you’ll see), but I guess that those approaches tend to stretch JavaScript’s limited support for classical OO concepts even more (and, as you probably know by now, is something I’d avoid at all costs).

Stay tuned for more on JavaScript.

Filed under:

Leave a Comment

(required) 
(required) 
(optional)
(required) 
If you can't read this number refresh your screen
Enter the numbers above:  

Search

This Blog

Tags

Community

Archives

Syndication

Email Notifications

News




  • View Luis Abreu's profile on LinkedIn


    Follow me at Twitter

    My books

    Silverlight 4.0: Curso Completo

    ASP.NET 4.0: Curso Completo

    Portuguese LINQ book cover

    Portuguese ASP.NET 3.5 book cover

    Portuguese ASP.NET AJAX book cover

    Portuguese ASP.NET AJAX book cover