EaselJS Inheritance

Synopsis: Creating custom classes that extend display objects.
Topics: inheritance, extend, promote
Target: EaselJS v0.8.0

This tutorial is part of the EaselJS GitHub repository.
Check out the repository for more tutorials and a handful of helpful samples.

Inheritance

Creating new class definitions that extend existing display objects provides encapsulated, easily reusable visual elements, and it's easy to do. This tutorial shows one method of extending a class, but there are many other options - use the one that's most comfortable for you, but apply the lessons you learn here.

We'll create a Button class, that extends Container.

Lines 1 & 15 create an anonymous function scope to work in and avoid polluting the global scope.

The constructor

Line 3 defines the constructor function which will be called when we create new Button instances. Line 4 calls Container's constructor, via a method alias that was set up by promote (more on that shortly). Calling the super class's constructor is very important to ensure new instances are set up correctly. Line 5 just sets the value of an instance property based on a parameter passed to the constructor.

Using createjs.extend()

Line 7 makes Button extend, or inherit from, the Container class. This adds Container to it's prototype chain, making all of its methods available in Button.

The extend method passes back the new prototype, which we assign to a new variable p for easy access.

Adding methods

Lines 9-12 set up a new draw method on Button's prototype, which overrides an existing draw method on Container. Just like with the constructor, it can call its super class's version of the method using a special method that was added by promote.

Using createjs.promote()

Line 14 calls promote, which identifies all of the methods in Container that were overridden in Button (including the constructor) and promotes them into Button with a new name in the format prefix_methodName. We specified "Container" as the prefix which results in promoted methods that look like Container_draw. This gives you an easy and highly performant way to call super class methods in the instance scope.

The promote method returns the class, which is then assigned into the global/window scope to make it available for our application.

Finishing up

Now the class can be instantiated, and added to the display list like any other display object.

Check out demo.html and Button.js to see an example of this in action. Click the buttons.