Handling API design and OO sugar

For now, you probably make it easiest on your library clients if you use a small API that helps you with building a traditional constructor function, using syntax that looks almost like prototypes-as-classes. Example API usage:

// Superclass
var Person = Class.extend({
    constructor: function (name) {
        this.name = name;
    },
    describe: function() {
        return "Person called "+this.name;
    }
});

// Subclass
var Worker = Person.extend({
    constructor: function (name, title) {
        Worker.super.constructor.call(this, name);
        this.title = title;
    },
    describe: function () {
        return Worker.super.describe.call(this)+" ("+this.title+")";
    }
});
var jane = new Worker("Jane", "CTO");

Implementations:

  • Simple JavaScript Inheritance
  • I’ve reimplemented Resig’s API, in a way that is possibly easier to understand: rauschma/class-js

Tags:

Javascript

Api