代碼如下:
//
//對象屬性復制方法,很多庫都有實現,如PrototypeJS里面的extend和Ext里面的Ext.apply
//
function extend(des, src) {
if (!des)
des = {};
if (src) {
for (var i in src) {
des[i] = src[i];
}
}
return des;
}
var CC = {}; //全局變量
//
//create 用于創建類
//
CC.create = function(superclass, constructor){
var clazz = (function() {
this.initialize.apply(this, arguments);
});
//如果無參數,直接返回類.
if(arguments.length == 0)
return clazz;
//如果無父類,此時constructor應該為一個純對象,直接復制屬性返回.
if(!superclass){
extend(clazz.prototype, constructor);
return clazz;
}
var absObj = clazz.prototype,
sprPropty = superclass.prototype;
if(sprPropty){
//用于訪問父類方法
clazz.superclass = sprPropty;
extend(absObj, sprPropty);
//調用屬性構造函數創建屬性,這個是實現關鍵.
extend(absObj, constructor(sprPropty));
// 子類實例直接通過obj.superclass訪問父類屬性,
// 如果不想造成過多引用,也可把這句注釋掉,因為多數時候是沒必要的.
absObj.superclass = sprPropty;
//
clazz.constructor = constructor;
}
return clazz;
}
//
//創建一個動物類
//
var Animal = CC.create(null, {
//屬性
footprint : '- - - - - - =',
//類初始化方法,必須的,當用 new 生成一個類時該方法自動被調用,參見上定義.
initialize : function(options){
extend(this, options);
alert('Animal initialize method is called.');
},
eat : function(){
alert('Animal eat method is called.');
},
move : function(){
alert('I am moving like this '+ this.footprint +' .');
}
});
//
//創建一個Duke類
//
var Duke = CC.create(Animal, function(superclass){
//在這可以定義一些類全局靜態數據,該類每個實例都共享這些數據.
//計算實例個類,包括派生類實例.
var static_instance_counter = 0;
function classUtilityFuncHere(){ }
//返回類具體屬性.
return {
//重寫初始化方法
//@override
initialize : function(options) {
alert('Initializing Duke class..');
//調用父類初始化,這種方法比一般其它庫的要簡潔點吧,可以不管父類是什么.
superclass.initialize.call(this, options);
//做一些子類喜歡做的事.
alert('Duke initialize method is called.');
//讀取或修改類靜態屬性
static_instance_counter++;
},
//重寫move方法,增加Duke自己的移動方式.
move : function(){
this.footprint = this.footprint + 'zzzzzzzz';
superclass.move.call(this);
},
//重寫eat方法,注意,里面不調用父類方法,即父類eat被覆蓋了.
eat : function(){
alert('Duke is eating..');
},
//新增一個say方法,顯示當前已經初始化的Duke類實例數量.
say : function(){
alert('the number of Duke instances is '+static_instance_counter);
}
};
});
var DukeChild = CC.create(Duke, function(superclass){
return {
move : function(){
this.footprint = this.footprint + '++++++++++++=';
superclass.move.call(this);
},
say : function(){
alert(this.msg || '');
}
};
});
(function test() {
var animal = new Animal();
animal.eat();
animal.move();
var dukeA = new Duke();
dukeA.eat();
dukeA.move();
dukeA.say();
var dukeB = new Duke();
dukeB.eat();
dukeB.move();
dukeB.say();
var dukeC = new DukeChild({msg : 'I am a child of duke.'});
dukeC.move();
dukeC.say();
})();
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com