Posted by & filed under Tips.

Class creation and specification of inheritance is carried out with the enchant.Class.create function. The first argument passed is an object used for defining the class. It is also common to pass an object literal, enclosed in curly brackets, for this argument. Specifically, the constructor method uses a key (“initialize”) to define the class.

var myClass = enchant.Class.create({
    initialize: function(name){ = name;
    sayHello: function(){
        alert('Hello! My name is' +;

var me = new myClass('Jack');
// -> == 'Jack'

// -> alert('My name is Jack');

To specify class inheritance, pass a parent class as the first argument of Class.create. In the following example, the newly defined Bear class will extend the Sprite class, but overrides the Sprite class’s initialize and walkTo functions.

var Bear = enchant.Class.create(enchant.Sprite, {
    initialize: function(){, 32, 32);
        this.x = 160;
        this.y = 160;
        this.image = game.assets['chara1.png'];
        this.frame = 5;
    walkTo: function(x, y){;{
            this.frame = this.age % 2 + 5;
        }, 30).and().moveTo(x, y, 30);

var bear = new Bear();

// Walk

Take a look at on the third line. If this function isn’t called, the Bear class will not move correctly.
This one line calls the new class constructor. In JavaScript, function objects contain the call method, and when called, execute the function. (Here, the context of the first argument [this] passes the following arguments to the function. It’s exactly the same as if new enchant.Sprite(32,32) was written.)
Since the walkTo method doesn’t exist in the Sprite class, we define it here for use by the Bear class.

This post is also available in: Japanese

Comments are closed.