Javascript 继承机制和构造方法链实现(原)
2014-05-03 00:34
579 查看
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的简称。^-^
以上实现了继承,多态,重载,和完整的构造体方法链。
相关文章推荐
- Javascript 继承机制和构造方法链实现
- 基于JavaScript实现继承机制之原型链(prototype chaining)的详解
- JavaScript中继承机制的模仿实现
- JavaScript实现继承机制(1)—— 构造函数方法对象冒充
- ECMAScript(JavaScript) 继承机制实现
- JavaScript面向对象的继承机制实现方式
- JavaScript中继承机制的模仿实现
- JavaScript继承机制的实现(未完)
- javascript继承机制的实现
- JavaScript中的继承机制的实现
- JavaScript中继承机制的实现
- 基于JavaScript实现继承机制之构造函数方法对象冒充的使用详解
- JavaScript简洁继承机制实现(不使用prototype和new)
- Javascript利用反射机制和prototype实现类的继承
- 基于JavaScript实现继承机制之调用call()与apply()的方法详解
- JavaScript继承机制模拟实现
- JavaScript实现继承机制(4)——构造函数+原型链混合方式
- 基于JavaScript实现继承机制之调用call()与apply()的方法详解
- JavaScript不使用prototype和new实现继承机制
- 基于JavaScript实现继承机制之原型链(prototype chaining)的详解