日期:2014-05-16 浏览次数:20478 次
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);