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 are creating and calling an anonymous wrapper function (to keep from polluting the global scope). On line 3 I am defining a new constructor function, then setting its prototype to a new
Container instance on line 6. This makes my new class inherit all of the properties and methods from
In the constructor on line 4, we call the
initialize method, and pass through the constructor parameters. The
initialize method handles all of the set up work for new instances, and it is vital that it gets called.
For this class, we are overriding
initialize method so that we can do some custom set up, however, we still need to make sure that the super class's
initialize method gets called. This is VERY important, especially for classes that inherit from
To do this, we are saving off the existing
initialize method (line 8), redefining it (line 9), and making sure that we call it first in the new method (line 10).
Finally, on line 14, we assign our class back 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 this in action.