Parasitic Inheritance in JavaScript

Posted by Daniel on February 01, 2008
Programming

In my previous post I talked about how to do prototypal inheritance in JavaScript, based on Doug’s presentation (which is part 1 of a 3-part series). In the same presentation, Doug introduces “Parasitic inheritance” in JavaScript, which is actually very much like classical inheritance, and it works remarkably well:

var Person = function(name, age) {
    /* "age" is a private variable */
    return {
        name: name,
        birthDate: function() {age += 1; return age;},
        setAge: function(n) {age = n;},
        getAge: function() {return age;}
    };
};

var Employee = function(name, age, group) {
    var e = Person(name, age);
    e.group = group;
    return e;
};

Notice that the sub-class Employee also has access to the private variable name. And how do we create objects? You can just call the functions:

var joe = Person("Joe", 31);
var sam = Employee("Sam", 24, "Sales");

Or if you prefer the traditional syntax:

var joe = new Person("Joe", 31);
var sam = new Employee("Sam", 24, "Sales");

The two options are equivalent, and they work the same!

And a neat property is that the objects created by these constructors are compatible with the prototypal inheritance we saw earlier:

/* object() defined in the previous post. */
var alice = object(joe);
alice.name = "Alice";
alice.setAge(27);

No comments yet.

Leave a comment

WP_Big_City

Buy cheap softwarebuy adobe softwaredownload software software sales oem software