Previous: Temporary Classes, Up: Defining Classes


2.1.7 Temporary Instances

Similar to Temporary Classes, you may wish to use an instance temporarily to invoke a method or chain of methods. Temporary instances are instances that are instantiated in order to invoke a method or chain of methods, then are immediately discarded.

    // retrieve the name from an instance of Foo
    var name = Foo().getName();

    // method chaining
    var car = VehicleFactory()
        .createBody()
        .addWheel( 4 )
        .addDoor( 2 )
        .build();

    // temporary class with callback
    HttpRequest( host, port ).get( path, function( data )
    {
        console.log( data );
    } );

    // Conventionally (without ease.js), you'd accomplish the above using
    // the 'new' keyword. You may still do this with ease.js, though it is
    // less clean looking.
    ( new Foo() ).someMethod();

Figure 2.9: Declaring a temporary (throwaway) class

Rather than storing the class instance, we are using it simply to invoke methods. The results of those methods are stored in the variable rather than the class instance. The instance is immediately discarded, since it is no longer able to be referenced, and is as such a temporary instance.

In order for method chaining to work, each method must return itself.

This pattern is useful for when a class requires instantiation in order to invoke a method. Classes that intend to be frequently used in this manner should declare static methods so that they may be accessed without the overhead of creating a new class instance.