Next: , Previous: Anonymous vs. Named Classes, Up: Defining Classes


2.1.5 Constructors

In JavaScript, we are used to functions themselves being a constructor because only constructors can be instantiated. With ease.js, constructors are handled in a manner similar to most other languages, by providing a separate method. The implementation ease.js chose is very similar to that of PHP's (see Constructor Implementation).

    var Foo = Class( 'Foo',
    {
        'public __construct': function( name )
        {
            console.log( 'Hello, ' + name + '!' );
        }
    } );

    // instantiate the class, invoking the constructor
    Foo( 'World' );

    // Output:
    // Hello, World!

Figure 2.6: Declaring constructors using ease.js

When the class is instantiated, the constructor is invoked, permitting you do to any necessary initialization tasks before the class can be used. The constructor operates exactly how you would expect a constructor to in JavaScript, with one major difference. Returning an object in the constructor does not return that object instead of the new class instance, since this does not make sense in a Class-based model.

If you wish to prevent a class from being instantiated, simply throw an exception within the constructor. This is useful if the class is intended to provide only static methods, or if you wish to enforce a single instance (one means of achieving a Singleton).

    var Foo = Class( 'Foo',
    {
        'public __construct': function( name )
        {
            throw Error( "Cannot instantiate class Foo" );
        }
    } );

Figure 2.7: Prevent class from being instantiated

Constructors are optional. By default, nothing is done after the class is instantiated.