Working With Classes
********************

In Object-Oriented programming, the most common term you are likely to encounter is ``Class''. A class is like a blueprint for creating an object, which is an instance of that class. Classes contain members, which include primarily properties and methods. A property is a value, much like a variable, that a class ``owns''. A method, when comparing with JavaScript, is a function that is ``owned'' by a class. As a consequence, properties and methods are not part of the global scope.

JavaScript does not support classes in the manner traditionally understood by Object-Oriented programmers. This is because JavaScript follows a different model which instead uses prototypes. Using this model, JavaScript supports basic instantiation and inheritance. Rather than instantiating classes, JavaScript instantiates constructors, which are functions. The following example illustrates how you would typically create a class-like object in JavaScript:

    /**
     * Declaring "classes" WITHOUT ease.js
     */

    // our "class"
    var MyClass = function()
    {
        this.prop = 'foobar';
    }

    // a class method
    MyClass.prototype.getProp = function()
    {
        return this.prop;
    };

    // create a new instance of the class and execute doStuff()
    var foo = new MyClass();
    console.log( foo.getProp() ); // outputs "foobar"
Figure: Basic ``Class'' in JavaScript without using ease.js

This gets the job done, but the prototypal paradigm has a number of limitations amongst its incredible flexibility. For Object-Oriented programmers, it's both alien and inadequate. That is not to say that it is not useful. In fact, it is so flexible that an entire Object-Oriented framework was able to be built atop of it.

ease.js aims to address the limitations of the prototype model and provide a familiar environment for Object-Oriented developers. Developers should not have to worry about how classes are implemented in JavaScript (indeed, those details should be encapsulated). You, as a developer, should be concerned with only how to declare and use the classes. If you do not understand what a prototype is, that should be perfectly fine. You shouldn't need to understand it in order to use the library (though, it's always good to understand what a prototype is when working with JavaScript).

In this chapter and those that follow, we will see the limitations that ease.js addresses. We will also see how to declare the classes using both prototypes and ease.js, until such a point where prototypes are no longer adequate.

Defining Classes
================

C = Class( string NAME, Object DFN )
     Define named class C identified by NAME described by DFN.

C = Class( string NAME ).extend( Object DFN )
     Define named class C identified by NAME described by DFN.

C = Class( Object DFN )
     Define anonymous class C as described by DFN.

C = Class.extend( Object DFN  )
     Define anonymous class C as described by DFN.

Class C can be defined in a number of manners, as listed above, provided a definition object DFN containing the class members and options. An optional string NAME may be provided to set an internal identifier for C, which may be used for reflection and error messages. If NAME is omitted, C will be declared anonymous.

Class must be imported (see Including) from easejs.Class; it is not available in the global scope.

Definition Object
-----------------

dfn = { '[KEYWORDS] NAME': VALUE[, ...] }
     Define definition object DFN containing a member identified by NAME, described by optional KEYWORDS with the value of VALUE. The member type is determined by typeof VALUE. Multiple members may be provided in a single definition object.

The definition object DFN has the following properties:

 1. The keys represent the member declaration, which may optionally contain one or more KEYWORDS delimited by spaces. A space must delimit the final keyword and NAME.

      1. KEYWORDS must consist only of recognized tokens, delimited by spaces.

      2. Each token in KEYWORDS must be unique per NAME.

 2. The VALUE represents the member definition, the type of which determines what type of member will be declared.

      1. A VALUE of type function will define a method, which is an invokable member whose context is assigned to the class or class instance depending on KEYWORDS.

      2. All other types of VALUE will define a property - a mutable value equal to VALUE, assigned to a class or instance depending on KEYWORDS.  Properties may be made immutable using KEYWORDS.

      3. Getters/setters may be defined in an ECMAScript 5 or greater environment. Getters/setters must share the same value for KEYWORDS.

 3. NAME must be unique across all members of DFN.

Member Validations
------------------

For any member NAME:

  * KEYWORDS of member NAME may contain only one access modifier (see Access Modifiers).

  * See Member Keywords for KEYWORDS restrictions.

For any member NAME declared as a method, the following must hold true:

  * KEYWORDS of member NAME may not contain override without a super method of the same NAME (see Inheritance).

  * KEYWORDS of member NAME may contain both static and virtual keywords (see Static Members and Inheritance).

  * KEYWORDS of member NAME may not contain the const keyword.

Discussion
----------

In f:class-js, we saw how one would conventionally declare a class-like object (a prototype) in JavaScript. This method is preferred for many developers, but it is important to recognize that there is a distinct difference between Prototypal and Classical Object-Oriented development models. Prototypes lack many of the conveniences and features that are provided by Classical languages, but they can be emulated with prototypes. As an Object-Oriented developer, you shouldn't concern yourself with how a class is declared in JavaScript. In true OO fashion, that behavior should be encapsulated. With ease.js, it is.

Let's take a look at how to declare that exact same class using ease.js:

    var Class = require( 'easejs' ).Class;

    var MyClass = Class(
    {
        'public prop': 'foobar',

        'public getProp': function()
        {
            return this.prop;
        }
    } );

    // create a new instance of the class and execute doStuff()
    var foo = MyClass();
    console.log( foo.getProp() ); // outputs "foobar"
Figure: Basic anonymous class declaration using ease.js

That should look much more familiar to Object-Oriented developers. There are a couple important notes before we continue evaluating this example:

  * The first thing you will likely notice is our use of the public keyword. This is optional (the default visibility is public), but always recommended. Future versions of ease.js may provide warnings when the visibility is omitted. We will get more into visibility later on.

  * Unlike f:class-js, we do not use the new keyword in order to instantiate our class. You are more than welcome to use the new keyword if you wish, but it is optional when using ease.js. This is mainly because without this feature, if the keyword is omitted, the constructor is called as a normal function, which could have highly negative consequences. This style of instantiation also has its benefits, which will be discussed later on.

  * ease.js's class module is imported using require() in the above example. If using ease.js client-side (see Client-Side Include), you can instead use var Class = easejs.Class. From this point on, importing the module will not be included in examples.

The above example declares an anonymous class, which is stored in the variable MYCLASS. By convention, we use CamelCase, with the first letter capital, for class names (and nothing else).

Anonymous vs. Named Classes
---------------------------

We state that f:class-easejs 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: 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
    foo.baz();

    // TypeError: Object #<anonymous> has no method 'baz'
Figure: 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
    foo.baz();

    // TypeError: Object #<MyFoo> has no method 'baz'
Figure: Declaring an empty named class

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

Constructors
------------

In JavaScript, we are used to functions themselves being a constructor because only constructors can be instantiated. With ease.js, constructors are handled in a manner similar to most other languages, by providing a separate method. The implementation ease.js chose is very similar to that of PHP's (see Constructor Implementation).

    var Foo = Class( 'Foo',
    {
        'public __construct': function( name )
        {
            console.log( 'Hello, ' + name + '!' );
        }
    } );

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

    // Output:
    // Hello, World!
Figure: Declaring constructors using ease.js

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

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

Temporary Classes
-----------------

In f:class-easejs, 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';
        }
    } )();

    foo.bar(); // returns 'baz'
Figure: Declaring a temporary (throwaway) class

In f:class-tmp 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.

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

Inheritance
===========

C' = Class( string NAME ).extend( Object BASE, Object DFN )
     Define named class C' identified by NAME as a subtype of BASE, described by DFN. BASE may be of type Class or may be any enumerable object.

C' = C.extend( Object DFN )
     Define anonymous class C' as a subtype of class C, described by DFN.

C' = Class.extend( Object BASE, Object DFN )
     Define anonymous class C' as a subtype of BASE, described by DFN. BASE may be of type Class or may be any enumerable object.

C is a class as defined in Defining Classes. BASE may be any class or object containing enumerable members. DFN is to be a definition object as defined in Definition Object.

Provided C or BASE to satisfy requirements of C, class C' will be defined as a subtype (child) of supertype (parent) class C. Provided BASE that does not satisfy requirements of C, C' will be functionally equivalent to a subtype of anonymous class B as defined by B = Class( BASE ).

Member Inheritance
------------------

Let DFN\_N\^C denote a member of DFN in regards to class C that matches (case-sensitive) name N and is not private. Let O\_N denote an override, represented as boolean value that is true under the condition that both DFN\_N\^C' and DFN\_N\^C are defined values.

C' will inherit all public and protected members of supertype C such that DFN\_N\^C' = DFN\_N\^C for each DFN\^C. For any positive condition O\_N, member DFN\_N\^C' will be said to override member DFN\_N\^C, provided that overriding member N passes all validation rules associated with the operation. A protected member may be escalated to public, but the reverse is untrue. private members are invisible to subtypes.

For any positive condition O\_N where member N is defined as a method:

  * One of the following conditions must always be true:

       * DFN\_N\^C is declared with the virtual keyword and DFN\_N\^C' is declared with the override keyword.

            * Note that DFN\_N\^C' will not become virtual by default (unlike languages such as C++); they must be explicitly declared as such.

       * DFN\_N\^C is declared with the abstract keyword and DFN\_N\^C' omits the override keywords.

  * The argument count of method DFN\_N\^C' must be >= the argument count of method DFN\_N\^C to permit polymorphism.

  * A reference to super method DFN\_N\^C will be preserved and assigned to this.__super within context of method DFN\_N\^C'.

  * A method is said to be concrete when it provides a definition and abstract when it provides only a declaration (see Definition Object).

       * Any method N such that DFN\_N\^C is declared abstract may be overridden by a concrete or abstract method DFN\_N\^C'.

       * A method N may not be declared abstract if DFN\_N\^C is concrete.

  * Member DFN\_N\^C' must be a method.

Members that have been declared static cannot be overridden (see Static Members).

Discussion
----------

Inheritance can be a touchy subject among many Object-Oriented developers due to encapsulation concerns and design considerations over method overrides. The decision of whether or not inheritance is an appropriate choice over composition is left to the developer; ease.js provides the facilities for achieving classical inheritance where it is desired.

Figure: Basic inheritance example

In the above example, we would say that LAZYDOG and TWOLEGGEDDOG are subtypes of DOG, and that DOG is the supertype of the two. We describe inheritance as an ``is a'' relationship. That is:

  * LAZYDOG is a DOG.

  * TWOLEGGEDDOG is also a DOG.

  * DOG is not a LAZYDOG or a TWOLEGGEDDOG.

Subtypes inherit all public and protected members of their supertypes (see Access Modifiers). This means that, in the case of our above example, the walk() and bark() methods would be available to our subtypes. If the subtype also defines a method of the same name, as was done above, it will override the parent functionality. For now, we will limit our discussion to public members. How would we represent these classes using ease.js?

    // our parent class (supertype)
    var Dog = Class( 'Dog',
    {
        'virtual public walk': function()
        {
            console.log( 'Walking the dog' );
        },

        'public bark': function()
        {
            console.log( 'Woof!' );
        }
    } );

    // subclass (child), as a named class
    var LazyDog = Class( 'LazyDog' ).extend( Dog,
    {
        'override public walk': function()
        {
            console.log( 'Lazy dog refuses to walk.' );
        }
    } );

    // subclass (child), as an anonymous class
    var TwoLeggedDog = Dog.extend(
    {
        'override public walk': function()
        {
            console.log( 'Walking the dog on two feet' );
        }
    } );
Figure: Inheritance in ease.js

You should already understand how to define a class (see Defining Classes). The above example introduced two means of extending classes -- defining a new class that inherits from a parent:

Named Subclasses
     LAZYDOG is defined as a named subclass (see Anonymous vs. Named Classes). This syntax requires the use of Class( 'Name' ). The extend() method then allows you to extend from an existing class by passing the class reference in as the first argument.

Anonymous Subclasses
     TWOLEGGEDDOG was declared as an anonymous subclass. The syntax for this declaration is a bit more concise, but you forfeit the benefits of named classes (see Anonymous vs. Named Classes). In this case, you can simply call the supertype's extend() method. Alternatively, you can use the Class.extend( Base, {} ) syntax, as was used with the named subclass LAZYDOG.

You are always recommended to use the named syntax when declaring classes in order to provide more useful error messages. If you are willing to deal with the less helpful error messages, feel free to use anonymous classes for their conciseness.

Understanding Member Inheritance
--------------------------------

In f:inheritance, we took a look at how to inherit from a parent class. What does it mean when we ``inherit'' from a parent? What are we inheriting? The answer is: the API.

There are two types of APIs that subtypes can inherit from their parents:

Public API
     This is the API that is accessible to everyone using your class. It contains all public members. We will be focusing on public members in this chapter.

Protected API
     Protected members make up a protected API, which is an API available to subclasses but not the outside world. This is discussed more in the Access Modifiers section (see Access Modifiers), so we're going to leave this untouched for now.

When a subtype inherits a member from its parent, it acts almost as if that member was defined in the class itself (This statement is not to imply that inheritance is a case of copy-and-paste. There are slight variations, which are discussed in more detail in the Access Modifiers section (see Access Modifiers).). This means that the subtype can use the inherited members as if they were its own (keep in mind that members also include properties). This means that we do not have to redefine the members in order to use them ourselves.

LAZYDOG and TWOLEGGEDDOG both inherit the walk() and bark() methods from the DOG supertype. Using LAZYDOG as an example, let's see what happens when we attempt to use the bark() method inherited from the parent.

    var LazyDog = Class( 'LazyDog' ).extend( Dog,
    {
        /**
         * Bark when we're poked
         */
        'public poke': function()
        {
            this.bark();
        }
    } );

    // poke() a new instance of LazyDog
    LazyDog().poke();

    // Output:
    // Woof!
Figure: Using inherited members

In f:using-inherited-members above, we added a poke() method to our LAZYDOG class. This method will call the bark() method that was inherited from DOG. If we actually run the example, you will notice that the dog does indeed bark, showing that we are able to call our parent's method even though we did not define it ourselves.

Overriding Methods
------------------

When a method is inherited, you have the option of either keeping the parent's implementation or overriding it to provide your own. When you override a method, you replace whatever functionality was defined by the parent. This concept was used to make our LAZYDOG lazy and our TWOLEGGEDDOG walk on two legs in f:inheritance.

After overriding a method, you may still want to invoke the parent's method. This allows you to augment the functionality rather than replacing it entirely.  ease.js provides a magic __super() method to do this. This method is defined only for the overriding methods and calls the parent method that was overridden.

In order to demonstrate this, let's add an additional subtype to our hierarchy. ANGRYDOG will be a subtype of LAZYDOG. Not only is this dog lazy, but he's rather moody.

    var AngryDog = Class( 'AngryDog' ).extend( LazyDog,
    {
        'public poke': function()
        {
            // augment the parent method
            console.log( 'Grrrrrr...' );

            // call the overridden method
            this.__super();
        }
    } );

    // poke a new AngryDog instance
    AngryDog().poke();

    // Output:
    // Grrrrrr...
    // Woof!
Figure: Using __super() method

If you remember from f:using-inherited-members, we added a poke() method to LAZYDOG. In f:super-method above, we are overriding this method so that ANGRYDOG growls when you poke him. However, we still want to invoke LAZYDOG's default behavior when he's poked, so we also call the __super() method. This will also make ANGRYDOG bark like LAZYDOG.

It is important to note that __super() must be invoked like any other method. That is, if the overridden method requires arguments, you must pass them to __super(). This allows you to modify the argument list before it is sent to the overridden method.

Type Checks and Polymorphism
----------------------------

The fact that the API of the parent is inherited is a very important detail. If the API of subtypes is guaranteed to be at least that of the parent, then this means that a function expecting a certain type can also work with any subtypes. This concept is referred to as polymorphism, and is a very powerful aspect of Object-Oriented programming.

Let's consider a dog trainer. A dog trainer can generally train any type of dog (technicalities aside), so it would stand to reason that we would want our dog trainer to be able to train LAZYDOG, ANGRYDOG, TWOLEGGEDDOG, or any other type of DOG that we may throw at him/her.

Figure: Class structure to demonstrate polymorphism

Type checks are traditionally performed in JavaScript using the instanceOf operator. While this can be used in most inheritance cases with ease.js, it is not recommended. Rather, you are encouraged to use ease.js's own methods for determining instance type (The reason for this will become clear in future chapters. ease.js's own methods permit checking for additional types, such as Interfaces.). Support for the instanceOf operator is not guaranteed.

Instead, you have two choices with ease.js:

Class.isInstanceOf( type, instance );
     Returns true if INSTANCE is of type TYPE. Otherwise, returns false.

Class.isA( type, instance );
     Alias for Class.isInstanceOf(). Permits code that may read better depending on circumstance and helps to convey the ``is a'' relationship that inheritance creates.

For example:

    var dog   = Dog()
        lazy  = LazyDog(),
        angry = AngryDog();

    Class.isInstanceOf( Dog, dog ); // true
    Class.isA( Dog, dog );          // true
    Class.isA( LazyDog, dog );      // false
    Class.isA( Dog, lazy );         // true
    Class.isA( Dog, angry );        // true

    // we must check an instance
    Class.isA( Dog, LazyDog ); // false; instance expected, class given
Figure: Using ease.js to determine instance type

It is important to note that, as demonstrated in f:instanceof-ex above, an instance must be passed as a second argument, not a class.

Using this method, we can ensure that the DOGTRAINER may only be used with an instance of DOG. It doesn't matter what instance of DOG - be it a LAZYDOG or otherwise. All that matters is that we are given a DOG.

    var DogTrainer = Class( 'DogTrainer',
    {
        'public __construct': function( dog )
        {
            // ensure that we are given an instance of Dog
            if ( Class.isA( Dog, dog ) === false )
            {
                throw TypeError( "Expected instance of Dog" );
            }
        }
    } );

    // these are all fine
    DogTrainer( Dog() );
    DogTrainer( LazyDog() );
    DogTrainer( AngryDog() );
    DogTrainer( TwoLeggedDog() );

    // this is not fine; we're passing the class itself
    DogTrainer( LazyDog );

    // nor is this fine, as it is not a dog
    DogTrainer( {} );
Figure: Polymorphism in ease.js

It is very important that you use only the API of the type that you are expecting. For example, only LAZYDOG and ANGRYDOG implement a poke() method. It is not a part of DOG's API. Therefore, it should not be used in the DOGTRAINER class. Instead, if you wished to use the poke() method, you should require that an instance of LAZYDOG be passed in, which would also permit ANGRYDOG (since it is a subtype of LAZYDOG).

Currently, it is necessary to perform this type check yourself. In future versions, ease.js will allow for argument type hinting/strict typing, which will automate this check for you.

Visibility Escalation
---------------------

Let A\_N denote a numeric level of visibility for DFN\_N\^C such that the access modifiers (see Access Modifiers) private, protected and public are associated with the values 1, 2 and 3 respectively. Let A' represent A in regards to C' (see Inheritance).

For any member N of DFN, the following must be true:

  * A'\_N >= A\_N.

  * DFN\_N\^C' cannot be redeclared without providing a new definition (VALUE).

Discussion
..........

Visibility escalation is the act of increasing the visibility of a member. Since private members cannot be inherited, this would then imply that the only act to be considered "escallation" would be increasing the level of visibility from protected to private.

Many follow the convention of prefixing private members with an underscore but leaving omitting such a prefix from protected members. This is to permit visibility escalation without renaming the member. Alternatively, a new member can be defined without the prefix that will simply call the overridden member (although this would then not be considered an escalation, since the member name varies).

In order to increase the visibility, you must override the member; you cannot simply redeclare it, leaving the parent definition in tact. For properties, this has no discernible effect unless the VALUE changes, as you are simply redefining it. For methods, this means that you are overriding the entire VALUE. Therefore, you will either have to provide an alternate implementation or call this.__super() to invoke the original method.

Note that you cannot de-escalate from public to protected; this will result in an error. This ensures that once a class defines an API, subclasses cannot alter it. That API must be forever for all subtypes to ensure that it remains polymorphic.

Let's take a look at an example.

    var Foo = Class(
        {
            'protected canEscalate': 'baz',

            'protected escalateMe': function( arg )
            {
                console.log( 'In escalateMe' );
            },

            'public cannotMakeProtected': function()
            {
            }
        } ),

        SubFoo = Foo.extend(
        {
            /**
             * Escalating a property means redefining it
             */
            'public canEscalate': 'baz',

            /**
             * We can go protected -> public
             */
            'public escalateMe': function( arg )
            {
                // simply call the parent method
                this.__super( arg );
            }
        } );
Figure: Visibility can be escalated

Note that, in the above example, making the public CANNOTMAKEPROTECTED method protected would throw an error.

Static Members
==============

Static members do not require instantiation of the containing class in order to be used, but may also be called by instances. They are attached to the class itself rather than an instance. Static members provide convenience under certain circumstances where class instantiation is unnecessary and permit sharing data between instances of a class. However, static members, when used improperly, can produce poorly designed classes and tightly coupled code that is also difficult to test. Static properties also introduce problems very similar to global variables.

Let us consider an implementation of the factory pattern.  Class BIGBANG will declare two static methods in order to satisfy different means of instantiation: fromBraneCollision() and fromBigCrunch() (for the sake of the example, we're not going to address every theory). Let us also consider that we want to keep track of the number of big bangs in our universe (perhaps to study whether or not a "Big Crunch" could have potentially happened in the past) by incrementing a counter each time a new big bang occurs. Because we are using a static method, we cannot use a property of an instance in order to store this data.  Therefore, we will use a static property of class BIGBANG.

    var BigBang = Class( 'BigBang',
    {
        /**
         * Number of big bangs that has occurred
         * @type {number}
         */
        'private static _count': 0,

        /**
         * String representing the type of big bang
         * @type {string}
         */
        'private _type': '',

        /**
         * Create a new big bang from the collision of two membranes
         *
         * @return  {BraneSet}  the set of branes that collided
         *
         * @return  {BigBang}  new big bang
         */
        'public static fromBraneCollision': function( brane_set )
        {
            // do initialization tasks...

            return BigBang( 'brane', brane_set.getData() );
        },

        /**
         * Create a new big bang following a "Big Crunch"
         *
         * @param  {BigCrunch}  prior crunch
         *
         * @return  {BigBang}  new big bang
         */
        'public static fromBigCrunch': function( crunch )
        {
            // do initialization tasks...

            return BigBang( 'crunch', crunch.getData() );
        },

        /**
         * Returns the total number of big bangs that have occurred
         *
         * @return  {number}  total number of big bangs
         */
        'public static getTotalCount': function()
        {
            return this.$('_count');
        }

        /**
         * Construct a new big bang
         *
         * @param  {string}  type  big bang type
         * @param  {object}  data  initialization data
         *
         * @return  {undefined}
         */
        'public __construct': function( type, data )
        {
            this._type = type;

            // do complicated stuff with data

            // increment big bang count
            this.__self.$( '_count',
                this.__self.$('count') + 1
            );
        },
    } );

    // create one of each
    var brane_bang  = BigBang.fromBraneCollision( branes ),
        crunch_bang = BigBang.fromBigCrunch( crunch_incident );

    console.log( "Total number of big bangs: %d", BigBang.getTotalCount() );
    // Total number of big bangs: 2
Figure: Static member example using the factory pattern

Due to limitations of pre-ECMAScript 5 implementations, ease.js's static implementation must be broken into two separate parts: properties and methods.

Static Methods
--------------

In f:static-ex, we implemented three static methods: two factory methods, fromBraneCollision() and FromBigCrunch(), and one getter method to retrieve the total number of big bangs, getTotalCount(). These methods are very similar to instance methods we are already used to, with a few important differences:

 1. Static methods are declared with the static keyword.

 2. In the body, this is bound to the class itself, rather than the instance.

 3. Static methods cannot call any non-static methods of the same class without first instantiating it.

The final rule above is not true when the situation is reversed. Non-static methods can call static methods through use of the __SELF object, which is a reference to the class itself. That is, THIS in a static method is the same object as THIS.__SELF in a non-static method. This is demonstrated by getTotalCount()

    this.$('_count')

and __construct().

    this.__self.$('_count')

To help remember __SELF, consider what the name states. A class is a definition used to create an object. The body of a method is a definition, which is defined on the class. Therefore, even though the body of a method may be called in the context of an instance, it is still part of the class. As such, __SELF refers to the class.

Static Properties
-----------------

You have likely noticed by now that static properties are handled a bit differently than both static methods and non-static properties. This difference is due to pre-ECMAScript 5 limitations and is discussed at length in the Static Implementation section.

Static properties are read from and written to using the static accessor method $(). This method name was chosen because the $ prefix is common in scripting languages such as BASH, Perl (for scalars) and PHP. The accessor method accepts two arguments, the second being optional. If only the first argument is provided, the accessor method acts as a getter, as in f:static-ex's getTotalCount():

    return this.$('_count');

If the second argument is provided, it acts as a setter, as in __construct():

    this.__self.$( '_count',
        this.__self.$('count') + 1
    );

Setting undefined values is supported. The delete operator is not supported, as its use is both restricted by the language itself and doesn't make sense to use in this context. As hinted by the example above, the increment and decrement operators (++ and --) are not supported because JavaScript does not permit returning values by reference.

It is important to understand that, currently, the accessor method cannot be omitted. Consider the following example:

    var Foo = Class( 'Foo',
        {
            'public static bar': 'baz',
        },

        SubFoo = Class( 'SubFoo' ).extend( Foo, {} )
    ;

    // correct
    Foo.$( 'bar, 'baz2' );
    Foo.$('bar');               // baz2
    SubFoo.$('bar');            // baz2
    SubFoo.$( 'bar', 'baz3' );
    Foo.$('bar');               // baz3

    // INCORRECT
    Foo.bar = 'baz2';
    Foo.bar;                    // baz2
    SubFoo.bar;                 // undefined
Figure: Static accessor method cannot be omitted

Constants
---------

Constants, in terms of classes, are immutable static properties. This means that, once defined, a constant cannot be modified. Since the value is immutable, it does not make sense to create instances of the property. As such, constant values are implicitly static. This ensures that each instance, as well as any static access, references the exact same value. This is especially important for objects and arrays.

One important difference between other languages, such as PHP, is that ease.js supports the visibility modifiers in conjunction with the const keyword. That is, you can have public, protected and private constants. Constants are public by default, like every other type of member. This feature permits encapsulating constant values, which is important if you want an immutable value that shouldn't be exposed to the rest of the world (e.g. a service URL, file path, etc). Consider the following example in which we have a class responsible for reading mount mounts from /etc/fstab:

    Class( 'MountPointIterator',
    {
        'private const _PATH': '/etc/fstab',

        'private _mountPoints': [],

        'public __construct': function()
        {
            var data = fs.readFileSync( this.$('_PATH') );
            this._parseMountPoints( data );
        },

        // ...
    } );
Figure: Using the const keyword

In the above example, attempting to access the _PATH constant from outside the class would return undefined. Had the constant been declared as public, or had the visibility modifier omitted, it could have been accessed just like any other static property:

    // if PATH were a public constant value
    MountPointIterator.$('PATH');

Any attempts to modify the value of a constant will result in an exception. This will also work in pre-ES5 engines due to use of the static accessor method ($()).

It is important to note that constants prevent the value of the property from being reassigned. It does not prevent modification of the value that is referenced by the property. For example, if we had a constant FOO, which references an object, such that

    'const foo': { a: 'b' }

it is perfectly legal to alter the object:

    MyClass.$('foo').a = 'c';