Javascript 繼承機制和構造方法鏈實現(原)

(function(){
Rs = {version: 1.0};

Rs.extend = function(target, params) {

target = target || {};

for (var prop in params) {
target[prop] = params[prop];
}
return target;
};

Rs.Class = function() {
// 構造體
var Class = function() {
this.initialize.apply(this, arguments);
};

var extended = {};

var parent, superclass;

for (var index = 0, len = arguments.length; index < len; index++) {

if (typeof arguments[index] == "function") {

// 如果有父類
if (index == 0 && len > 1) {

var initialize = arguments[index].prototype.initialize;

arguments[index].prototype.initialize = function() {};

extended = new arguments[index]();

if (initialize === undefined) {
delete arguments[index].prototype.initialize;
} else {
arguments[index].prototype.initialize = initialize;
}

superclass = arguments[index];
continue;
}

parent = arguments[index].prototype;
} else {
// 如果爲頂層基類
parent = arguments[index];
}

Rs.extend(extended, parent);
}
Class.prototype = extended;
Class.superclass = superclass;
return Class;
};
})();

var Animal = Rs.Class({
initialize: function(name){

this.name = name;
},

showName: function(){
alert(this.name);
}
});

var Cat = Rs.Class(Animal, {
initialize: function(name) {
// 調用父類構造函數
Cat.superclass.prototype.initialize.call(this, name);
}
});

var BlackCat = Rs.Class(Cat, {
initialize: function(name, type) {
// 調用父類構造函數
BlackCat.superclass.prototype.initialize.call(this, name);
this.type = type;
},
showType: function() {
alert(this.type);
},
showName: function() {
alert(this.name + ":" + this.type);
}
});


var cat = new Cat("cat name");

// 繼承方法
cat.showName();

// true
alert(cat instanceof Animal);

// true
alert(cat instanceof Cat);

// false
alert(cat instanceof BlackCat);

var blackCat = new BlackCat("123", "black");

// 方法重寫
blackCat.showName();

// 自有方法
blackCat.showType();

// true
alert(blackCat instanceof Animal);

// true
alert(blackCat instanceof Cat);

// true
alert(blackCat instanceof BlackCat);


大家可能會問,Rs是什麼,Rs就是Rainsilence的簡稱。^-^

以上實現了繼承,多態,重載,和完整的構造體方法鏈。
發佈了12 篇原創文章 · 獲贊 1 · 訪問量 2533
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章