Fundamentals

The following code creates a new class Counter using Core.extend():

Counter = Core.extend({

    count: 0,
    defaultIncrement: 1,

    $construct: function(defaultIncrement) {
        if (defaultIncrement) {
            this.defaultIncrement = defaultIncrement;
        }
    },

    increment: function(amount) {
        if (amount) {
            this.count += amount;
        } else {
            this.count += this.defaultIncrement;
        }
    }
});

Core.extend() is passed an object definition which instructs it as to how a new class should be created. Note that the object definition is written using JavaScript's Object Literal syntax. Core.extend() will process the provided object and return a new class (constructor), which we then assign to the Counter variable.

Any properties that do not begin with a dollar sign ($) are added to the prototype of the class (constructor). Properties that do begin with the dollar sign are interpreted specially. The value of the $construct property, is used as the constructor.

In the above example, the variables count and defaultIncrement are added to the class prototype with values of 0 and 1 respectively. One method is defined, increment() which increments the value of count. The $construct property defines a constructor which sets the defaultIncrement property to a specific value if one is provided.

Instantiating the class is accomplished in the traditional fashion, for example:

// Creates a counter with a defaultIncrement of 1.
var counter1 = new Counter();

// Creates a counter with a defaultIncrement of 5.
var counter2 = new Counter(5); 

CAUTION: A Warning About Properties

It's important to realize that all properties that do not begin with a dollar sign ($) are added to the prototype. This means that any such property will be copied into any instance of an object created. Properties that are held by reference, e.g., Objects will simply have the reference copied (the object will not be cloned).

Take for example the following code:

BadIdea = Core.extend({

     anArray: new Array();
});

In this code, one array instance will be shared by all instances of BadIdea. Chances are this is not what you want. The reason you'll want to watch out for this is because Core.extend() makes instance variables above look an awful lot like they might in Java or C#. In those languages, such initial values are installed for each instance of the object. In JavaScript, they are not.

A better way to go about declaring instance variables is the following:

GoodIdea = Core.extend({

    anArray: null,

    $construct: function() {
        this.anArray = new Array();
    }
});

Technically you don't have to declare "anArray" at all, but you'll learn why it's not a bad idea to do so in later sections.