Next: , Previous: , Up: Defining Classes   [Contents]


2.1.6 Constructors

A “constructor” in JavaScript is simply a function—whether or not it actually constructs a new object depends on whether the tt keyword is used. With ease.js, constructors are handled in a manner similar to most other languages: by providing a separate method.

Until the release of ECMAScript 6, which introduced the class keyword, there was no convention for constructors defined in this manner. The implementation ease.js chose is very similar to that of PHP’s (see Constructor Implementation):

    var Foo = Class( 'Foo',
    {
        // may also use `construct`; see below
        __construct: function( name )
        {
            console.log( 'Hello, ' + name + '!' );
        }
    } );

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

    // Output:
    // Hello, World!

Figure 2.9: Declaring constructors using ease.js

ease.js introduced the constructor method in version 0.2.7 to match the ES6 “class” implementation; it is an alias for __construct. This method name may be used prior to ES6.

    // ECMAScript 6 syntax
    let Foo = Class( 'Foo',
    {
        // you may still use __construct
        constructor( name )
        {
            console.log( 'Hello, ' + name + '!' );
        }
    } );

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

    // Output:
    // Hello, World!

Figure 2.10: Declaring constructors in an ECMAScript 6 style

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.11: Prevent class from being instantiated

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


Next: , Previous: , Up: Defining Classes   [Contents]