js不好继承,用的时候都是一些很奇怪的方法,比如call,再比如如下
function a(){
this.b = 1
}
function b() {
this.parent =a;
this.parent();
delete this.parent;
}
然后再prototype
for() {
xxxx
}
看起来好丑啊,完全没有韵味,琢磨着,对Function 加个extend方法,然后就有了下边的代码:
Function.prototype.extend = function(parent) {
var _this = this;
var child = function(){
this.parent = parent;
this.parent.apply(this,arguments);
this.me = _this;
this.me.apply(this,arguments);
delete this.parent;
delete this.me;
}
for(var k in parent.prototype) {
child.prototype[k] = parent.prototype[k]
}
return child;
}
然后来做个实验
function a(c) {
this.v_1 = c;
this.setV = function(v) {
this.v_1 = v;
}
}
a.prototype.show = function(){
alert(this.v_1);
}
var b = function(){
this.v_2 = 2;
this.setV2 = function(v) {
this.v_2 = v;
}
}.extend(a);
var c = new b(8);
c.show();
c.setV(2);
c.show();
alert(c.v_2);
c.setV2(3);
alert(c.v_2);
看来看去也没有什么问题,希望高手进来探讨探讨