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){
        this.name = name;
    },
    sayHello: function(){
        alert('Hello! My name is' + this.name);
    }
});

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

me.sayHello();
// -> 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(){
        enchant.Sprite.call(this, 32, 32);
        this.x = 160;
        this.y = 160;
        this.image = game.assets['chara1.png'];
        this.frame = 5;
    },
    walkTo: function(x, y){
        this.tl.clear();
        this.tl.repeat(function(){
            this.frame = this.age % 2 + 5;
        }, 30).and().moveTo(x, y, 30);
    }
});

var bear = new Bear();
game.rootScene.addChild(bear);

// Walk
bear.walkTo();

Take a look at enchant.Sprite.call 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.