摘自Object Oriented Javascript 一书
基于临时函数的继承机制
先上代码:
/* Temporary constructor */
function Shape() { }
Shape.prototype.name = 'Shape';
Shape.prototype.toString = function() {
return this.name;
};
function Shape2D() { }
function A() { }
A.prototype = Shape.prototype;
Shape2D.prototype = new A();
Shape2D.prototype.constructor = Shape2D;
Shape2D.prototype.name = 'Shape 2D';
function Triangle(side, height) {
this.side = side;
this.height = height;
}
function B() { }
B.prototype = Shape2D.prototype;
Triangle.prototype = new B();
Triangle.prototype.constructor = Triangle;
Triangle.prototype.name = 'Triangle';
Triangle.prototype.getArea = function() {
return this.side * this.height / 2;
}
// test
var t = new Triangle(10, 10);
console.log(t.getArea());
console.log(t.toString()); // 输出 Triangle
var s = new Shape();
console.log(s.toString()); // 输出 Shape
var s2d = new Shape2D();
console.log(s2d.toString()); // 输出 Shape 2D
再上对象关系图: