Next: , Previous: , Up: Top   [Contents]

2 Working With Classes

In Object-Oriented programming, the most common term you are likely to encounter is “Class”. A class is like a blueprint for creating an object, which is an instance of that class. Classes contain members, which include primarily properties and methods. A property is a value, much like a variable, that a class “owns”. A method, when comparing with JavaScript, is a function that is “owned” by a class. As a consequence, properties and methods are not part of the global scope.

JavaScript does not support classes in the manner traditionally understood by Object-Oriented programmers. This is because JavaScript follows a different model which instead uses prototypes. Using this model, JavaScript supports basic instantiation and inheritance. Rather than instantiating classes, JavaScript instantiates constructors, which are functions. The following example illustrates how you would typically create a class-like object in JavaScript:

     * Declaring "classes" WITHOUT ease.js

    // our "class"
    var MyClass = function()
        this.prop = 'foobar';

    // a class method
    MyClass.prototype.getProp = function()
        return this.prop;

    // create a new instance of the class and execute doStuff()
    var foo = new MyClass();
    console.log( foo.getProp() ); // outputs "foobar"

Figure 2.1: Basic “Class” in JavaScript without using ease.js

This gets the job done, but the prototypal paradigm has a number of limitations amongst its incredible flexibility. For Object-Oriented programmers, it’s both alien and inadequate. That is not to say that it is not useful. In fact, it is so flexible that an entire Object-Oriented framework was able to be built atop of it.

ease.js aims to address the limitations of the prototype model and provide a familiar environment for Object-Oriented developers. Developers should not have to worry about how classes are implemented in JavaScript (indeed, those details should be encapsulated). You, as a developer, should be concerned with only how to declare and use the classes. If you do not understand what a prototype is, that should be perfectly fine. You shouldn’t need to understand it in order to use the library (though, it’s always good to understand what a prototype is when working with JavaScript).

In this chapter and those that follow, we will see the limitations that ease.js addresses. We will also see how to declare the classes using both prototypes and ease.js, until such a point where prototypes are no longer adequate.

Next: , Previous: , Up: Top   [Contents]