Javascript継承メカニズムと構造方法チェーンの実現(元)
3118 ワード
(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の略称です.以上は継承,多状態,重荷重,および完全な構造体法鎖を実現した.