Defining Classes in AFrameJS

Along with the updates to make object instantiation easier in AFrameJS, defining classes for the "80% case" has become much simpler.

In AFrameJS, most class constructors do absolutely nothing other than call its superclass constructor. Object initialization is deferred until the init function. The reason for this is so that Plugins can be created and bound to an object before the object is ever operated on. The late initialization allows Plugins to do things like place decorators on functions on the object, all of this happening before the object is operated on. 80% of the time, this is all that a constructor needs to do.

After developing a lot of classes, I began seeing this repeated over and over again:

var Class = function() {
    Class.sc.constructor.call( this );
};
AFrame.extend( Class, SuperClass, {
   // more code
} );

Identical class constructors as well as the AFrame.extend were being repeated over and over again. Booo..

A Better Way

It just made sense to combine all that repeated logic and cut down on that code. There is a shortcut now, AFrame.Class.

Defining a Class That Has a Superclass

The above example is reworked as:

var Class = AFrame.Class( SuperClass, {
   // more code
} );

Much simpler, isn't it?

Defining a Class That Does Not Have a Superclass

If your class has no superclass, even easier

var Class = AFrame.Class( {
   // more code
} );

A working example of these two in action can be found on JSFiddle.

The 20% Case - Your Constructor Needs to Do Something

If for some reason your class constructor needs to do something critically important, you can still do this, it just takes a bit more work. We'll just go back to the old way of doing this as outlined above.

var Class = function() {
    Class.sc.constructor.call( this );
};
AFrame.extend( Class, SuperClass, {
   // more code
} );

That's all there is to it. Less code. Same functionality. Just as much if not more readability.