This tutorial is part of the EaselJS GitHub repository.
Check out the repository for more tutorials and a handful of helpful samples.
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
Lines 1 & 15 create an anonymous function scope to work in and avoid polluting the global scope.
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.
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.
extend method passes back the
new prototype, which we assign to a new variable
p for easy access.
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
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
We specified "Container" as the prefix which results in promoted methods that look like
This gives you an easy and highly performant way to call super class methods in the instance scope.
promote method returns the class, which is then assigned into the global/window scope to make it available for our application.
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.