cocos2d JS,JavaScript JavaScript 中的简单继承关系

JavaScript 语言本身没有提供类,没有其他语言的类继承机制,它的继承时通过对象的原型实现的,但这不能满足我们对 Cocos2d-JS 引擎的要求,所有类都直接或间接继承实现的。

var Person = Class.extend({ //声明一个Person类,继承自 Class,Class.extend()表示继承自Class

init: function(isDancing){ //定义构造函数init初始化属性

this.dancing = isDancing;

},

dance: function () { //定义普通函数dance(),返回属性dancing

return this.dancing;

}

});

var Ninja = Person.extend({ //声明Ninja类继承自 Person 类

init: function () { //定义构造函数 init,在该函数中 this._super(false) 语句时调用父类构造函数初始化父类中的属性

this._super(false);

},

dance: function (){ // 重写 dance() 函数,它会覆盖父类的 dance() 函数

//Call the inherited version of dance()

return this._super( ); //调用父类的 dance() 函数

},

swingSword: function () { //这个函数是子类 Ninja 新添加的函数 swingSword()

return true;

}

});

var p = new Person(true); //通过 Person 类创建 p 对象,给构造函数的参数是 true

console.log(p.dance()); //打印 p 对象 dance 属性 -> true

var n = new Ninja(); //通过 Ninja 类创建 n 对象,构造函数位空,默认初始化采用 fales 初始化父类中的 dance 属性,打印为 false

console.log(n.dance()); //false

console.log(n.swingSword()); //true

这种简单的 JavaScript 继承方法事实上实现了一般意义上的面向对象概念的继承和多态机制,这种继承方法是 Cocos2d-Js 继承机制的核心。