JavaScript继承还有一种继承模式——寄生继承。
举个例子:
function object(o) {
function F() {};
F.prototype = o;
return new F();
}
var twoD = {
name: '2D shape',
dimensions: 2
}
function triangle(s, h) {
var that = object(twoD);
that.name = 'Triangle';
that.getArea = function() {return this.side*this.height / 2;}
that.side = s;
that.height = h;
return that;
}
var a = triangle(2,16);
a.dimensions
寄生继承首先将一个普通对象twoD克隆进一个叫that的对象,然后扩展that对象,添加更多的属性,最后返回that对象。这种寄生继承就是对原型继承的第二次封装,并且在这第二次封装过程中对继承的对象进行了拓展,这项新创建的对象不仅仅有父类中的属性和方法而且还有新添加的属性和方法。