js継承実現
3067 ワード
多くのjs継承の実現を見ましたが、このコードの継承の実現はより良いものであり、extjsの継承メカニズムと非常に似ているようです.
/**
*
* @param target
* @param params
*/
function extend(target, params) {
if (!target) {
target = {};
}
for (var prop in params) {
target[prop] = params[prop];
}
return target;
}
/**
*
* @param SuperClass
* @param overrides
*/
function extendClass(SuperClass, overrides) {
var SubClass = function() {
//
this.initialize.apply(this, arguments);
};
SubClass.prototype = new SuperClass();
extend(SubClass.prototype, overrides);
SubClass.superclass = SuperClass;
return SubClass;
}
使い方var Animal = extendClass(Object, {
initialize: function(name){
this.name = name;
},
showName: function(){
alert(this.name);
}
});
var Cat = extendClass(Animal, {
initialize: function(name) {
//
Cat.superclass.prototype.initialize.call(this, name);
}
});
var BlackCat = extendClass(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);