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的简称。^-^

以上实现了继承,多态,重载,和完整的构造体方法链。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值