AlloyRenderingEngine繼承
2015-04-28 14:59 【當耐特】 閱讀(1088) 評論(1) 收藏 舉報寫在前面
不讀文章,只對代碼感興趣可以直接跳轉到這里 https://github.com/AlloyTeam/AlloyGameEngine
然后star一下,多謝支持:)。
前幾天發(fā)了篇向ES6靠齊的Class.js,當初jr為什么不把父類的實例暴露給子類,其原因還是為了延續(xù)原型繼承的習慣,子類重寫就會覆蓋掉父類的方法,父類的方法就會丟,如下面的代碼,就堆棧溢出了:
var Parent = function () {
}
Parent.prototype.a = function () {
}
var Child = function () {
}
Child.prototype = new Parent();
Child.prototype.a = function () {
this.a();
}
var child = new Child();
child.a();而jr的Class.js可以讓你通過this._super訪問父類同類方法,修復了原型繼承同名無法訪問父類的弱點,當然也可以hack一下,先賦給變量或者某個屬性。如:
var Parent = function () {
}
Parent.prototype.a = function () {
alert(1)
}
var Child = function () {
}
Child.prototype = new Parent();
Child.prototype.parentA = Child.prototype.a;
Child.prototype.a = function () {
this.parentA();
}
var child = new Child();
child.a();但是這樣的話,代碼不就很丑陋了嗎!?
所以AlloyRenderingEngine選擇使用了JR的Class.js,然后在其基礎之上擴展了靜態(tài)方法和屬性,以及靜態(tài)構造函數(shù)。
所以就變成了這樣:
var Person = Class.extend({
statics:{
//靜態(tài)構造函數(shù)會直接被Class.js執(zhí)行
ctor:function(){
//這里的this相當于Person
},
Version:"1.0.0",
GetVersion:function(){
return Person.Version;
}
},
ctor: function(isDancing){
this.dancing = isDancing;
},
dance: function(){
return this.dancing;
}
});
var Ninja = Person.extend({
ctor: function(){
this._super( false );
},
dance: function(){
// Call the inherited version of dance()
return this._super();
},
swingSword: function(){
return true;
}
});AlloyRenderingEngine繼承
AlloyRenderingEngine內置了Container對象,用來管理元素,Stage對象也是繼承自Container對象,
還有,Container對象繼承自DisplayObject,所以Container對象也能夠設置scale、x、y、alpha、rotation、compositeOperation…等,設置的屬性能夠疊加到子元素上。
x、y、rotation、scaleX、scaleY、skewX、skewY…等直接矩陣疊加,也就是子元素的呈現(xiàn)跟父容器、父容器的父容器、父容器的父容器的父容器…都有關系;
其實alpha是乘法疊加(如:容器的透明度是0.5,容器內部的元素透明度為0.9,最后容器內部元素呈現(xiàn)的透明度就是0.45);;
compositeOperation先查找自己,自己沒定義,再向上查找,直到找到定義了compositeOperation的,就使用該compositeOperation,有點類似決定定位元素找父容器的感覺。
很多情況下,我們需要繼承Container對象來封裝一些自定義的對象。
比如封裝一個按鈕:
var Button = Container.extend({
ctor: function (image) {
this._super();
this.bitmap = new Bitmap(image);
this.bitmap.originX = this.bitmap.originY = 0.5;
this.add(this.bitmap);
//鼠標指針的形狀
this.cursor = "pointer";
this._bindEvent();
},
_bindEvent: function () {
this.onHover(function () {
this.scale = 1.1;
}, function () {
this.scale = 1.0;
})
this.onMouseDown(function () {
this.scale = 0.9;
})
this.onMouseUp(function () {
this.scale = 1.1;
})
}
});使用這個button就很方便了:
var stage = new Stage("#ourCanvas");
var button = new Button("button.png");
button.x = 100;
button.y = 100;
button.onClick(function () {
console.log("你點擊我了");
})
stage.add(button);簡單吧!
在線演示
地址
Class.js:https://github.com/AlloyTeam/AlloyGameEngine/blob/master/src/are/base.js
AlloyGameEngine:https://github.com/AlloyTeam/AlloyGameEngine
浙公網(wǎng)安備 33010602011771號