Static Initializers and Class Properties

Class Properties

Core.extend() also provides a syntax for adding properties directly to a class' constructor, rather than to its prototype. Any properties that are added directly to a constructor (rather than the prototype) become class properties, i.e., they are not associated with any particular instance of the class. A $static block is used in Core.extend() declarations to describe any class properties:

ExampleClass = Core.extend({
    $static: {

        staticValue: 12,

        staticMethod: function(x) {
            return this.staticValue + x;
        }
    },

    instanceValue: 50,

    instanceMethod: function(x) {
        return ExampleClass.staticValue + this.instanceValue + x;
    }
});

In the case of the above ExampleClass, staticValue and staticMethod are added directly to the class, while instanceValue and instanceMethod are specific to/operate on individual instances of the class.

Inside of a static method, such as staticMethod(), the this pointer refers to the ExampleClass object itself. Thus we can refer to ExampleClass.staticValue as this.staticValue.

If we wish to call the static method or refer to the static value from anywhere other than a static method of ExampleClass, we must refer to them as ExampleClass.staticValue and ExampleClass.staticMethod().

It is important to note that we cannot refer to a static property using the this pointer from inside an instance method. The this-pointer will refer to our instance, not the class itself in such a case. For example, the following implementation of instanceMethod() would not work as expected:

    instanceMethod: function(x) {
        // FAIL:
        return this.staticValue + this.instanceValue + x;
    }

Class properties are not inherited by subclasses. For example, if we were to extend ExampleClass, we would still need to refer to staticValue as ExampleClass.staticValue.

Static Initializers

A static initializer is a constructor-like method that is invoked when a class is initially declared by Core.extend(). Such initializers can be used to perform setup work on a class. To use static initializers with Core.extend() you define a $load() method:

StaticInitializerExample = Core.extend({
    $load: function() {
        this.aStaticValue = "foo";
        SomeSubSystem.registerClass("staticInitializerExample", this);
    }
});

Note that the this pointer refers to the class being declared. When writing a static initializer, beware that the class has not yet been declared and is not assigned to its global variable yet. For example, the following code will fail, because the variable Failure is still undefined when the static initializer is executed:

Failure = Core.extend({
    $load: function() {
        Failure.thisIsGonnaFail = "FAIL!";
    }
});