Previous: , Up: Defining Classes [Contents]


2.1.8 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.13: 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.

Part of the GNU Project

Copyright © 2011, 2012, 2013, 2014, 2015, 2016 Free Software Foundation, Inc.

"GNU Inside!" Page Fold licensed under CC-BY-SA 2.0; incorporates "A Big GNU Head".

The source code of this website is available in the website branch of the Git repository.

Authored by Mike Gerwitz

AltStyle によって変換されたページ (->オリジナル) /