Simple classes

JavaScript has objects, which through the object tree support inheritance. Almost all object-oriented languages have classes and instances, but JavaScript has neither. This will be explained later, along with a discussion of the consequences.

For now our focus is on getting going with object-oriented programming. The easiest way to do this is via create.

Definition

Here’s a factory function that creates classes. It returns a function called cls, which in turn when called returns instances. At it’s heart is create, and also apply and arguments, which we’ve not seen before).

var SimpleClass = function(prototype){

    var cls = function(){

        var instance = create(prototype);
        instance.__init__.apply(instance, arguments);
        return instance;
    };

    return cls;
};

Why cls?

We call the returned function cls because in JavaScript class, like function is a reserved word in JavaScript. However, in JavaScript the identifier class has no meaning, and cannot be used in any valid JavaScript program. It seems that they intended to provide a built-in class capability, but never got round to it.

Fruit example

Here’s an example of the use of SimpleClass. There’s a bug in it, and I’ve changed the test so it passes. Can you find the bug and fix the example?

TEST('SimpleClass', function()
{
    var fruit = {};

    fruit.__init__ = function(name, colour){

        this.name = name;
        this.colour = colour;
    };

    fruit.greet = function(){

        return "Hello, I'm a " + this.color + " " + this.name + ".";
    };

    var Fruit = SimpleClass(fruit);

    var bn = Fruit('banana', 'yellow');
    var rc = Fruit('cherry', 'red');
    var gs = Fruit('Granny Smith', 'green');

    assert( bn.greet() === "Hello, I'm a undefined banana." );

});