Next: , Up: Defining Classes

2.1.4 Anonymous vs. Named Classes

We state that Figure 2.2 declared an anyonmous class because the class was not given a name. Rather, it was simply assigned to a variable, which itself has a name. To help keep this idea straight, consider the common act of creating anonymous functions in JavaScript:

    // anonymous
    var myFunc = function() {};

    // named
    function myNamedFunc() {};

Figure 2.3: Anonymous functions in JavaScript

If the function itself is not given a name, it is considered to be anonymous, even though it is stored within a variable. Just as the engine has no idea what that function is named, ease.js has no idea what the class is named because it does not have access to the name of the variable to which it was assigned.

Names are not required for classes, but they are recommended. For example, consider what may happen when your class is output in an error message.

    // call non-existent method

    // TypeError: Object #<anonymous> has no method 'baz'

Figure 2.4: Anonymous classes do not make for useful error messages

If you have more than a couple classes in your software, that error message is not too much help. You are left relying on the stack trace to track down the error. This same output applies to converting a class to a string or viewing it in a debugger. It is simply not helpful. If anything, it is confusing. If you've debugged large JS applications that make liberal use of anonymous functions, you might be able to understand that frustration.

Fortunately, ease.js permits you to declare a named class. A named class is simply a class that is assigned a string for its name, so that error messages, debuggers, etc provide more useful information. There is functionally no difference between named and anonymous classes.

    var MyFoo = Class( 'MyFoo', {} ),
        foo   = MyFoo();

    // call non-existent method

    // TypeError: Object #<MyFoo> has no method 'baz'

Figure 2.5: Declaring an empty named class

Much better! We now have a useful error message and immediately know which class is causing the issue.