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

2.1.7 Temporary Classes

In Figure 2.2, we saw that the new keyword was unnecessary when instantiating classes. This permits a form of shorthand that is very useful for creating temporary classes, or “throwaway“ classes which are used only once.

Consider the following example:

    // new instance of anonymous class
    var foo = Class(
        'public bar': function()
            return 'baz';
    } )();; // returns 'baz'

Figure 2.12: Declaring a temporary (throwaway) class

In Figure 2.12 above, rather than declaring a class, storing that in a variable, then instantiating it separately, we are doing it in a single command. Notice the parenthesis at the end of the statement. This invokes the constructor. Since the new keyword is unnecessary, a new instance of the class is stored in the variable foo.

We call this a temporary class because it is used only to create a single instance. The class is then never referenced again. Therefore, we needn’t even store it - it’s throwaway.

The downside of this feature is that it is difficult to notice unless the reader is paying very close attention. There is no keyword to tip them off. Therefore, it is very important to clearly document that you are storing an instance in the variable rather than an actual class definition. If you follow the CamelCase convention for class names, then simply do not capitalize the first letter of the destination variable for the instance.