Next: , Up: Class Module Design


B.1.1 Class Declaration Syntax

Much thought was put into how a class should be declared. The chosen style serves as syntatic sugar, making the declarations appear very similar to classes in other Object-Oriented languages.

The original style was based on John Resig's blog post about a basic means of extending class-like objects (see About). That style was ‘Class.extend()’ to declare a new class and ‘Foo.extend()’ to extend an existing class. This implementation is still supported for creating anonymous classes. However, a means needed to be provided to create named classes. In addition, invoking extend() on an empty class seemed unnecessary.

The next incarnation made the Class module invokable. Anonymous classes could be defined using ‘Class( {} )’ and named classes could be defined by passing in a string as the first argument: ‘Class( 'Foo', {} )’. Classes could still be extended using the previously mentioned syntax, but that did no justice if we need to provide a class name. Therefore, the ‘Class( 'SubFoo' ).extend( Supertype, {} )’ syntax was also adopted.

JavaScript's use of curly braces to represent objects provides a very convenient means of making class definitions look like actual class definitions. By convention, the opening brace for the declaration object is on its own line, to make it look like an opening block.

    Class( 'Foo' )
        .implement( Bar )
        .extend(
    {
        'public foo': function()
        {
        }
    } );

Figure B.1: Syntax and style of class definition

Syntax for implementing interfaces and extending classes was another consideration. The implementation shown above was chosen for a couple of reasons. Firstly, verbs were chosen in order to (a) prevent the use of reserved words and (b) to represent that the process was taking place at runtime, as the code was being executed. Unlike a language like C++ or Java, the classes are not prepared at compile-time.