我试图弄清楚下面的代码是如何工作的。有人能解释一下“创建一个指向父原型对象的超级属性”是什么意思吗?当它说“this.constructor.uber”指向父母的原型时,究竟是什么意思?我一直在挠头有一段时间了。如果有人能解释函数 Shape() 中发生了什么,我将非常感激。
function Shape() {}
// augment prototype
Shape.prototype.name = 'shape';
Shape.prototype.toString = function () {
var result = [];
if (this.constructor.uber) {
result[result.length] = this.constructor.uber.toString();
}
result[result.length] = this.name;
return result.join(', ');
};
function TwoDShape() {}
// take care of inheritance
var F = function () {};
F.prototype = Shape.prototype;
TwoDShape.prototype = new F();
TwoDShape.prototype.constructor = TwoDShape;
TwoDShape.uber = Shape.prototype;
// augment prototype
TwoDShape.prototype.name = '2D shape';
function Triangle(side, height) {
this.side = side;
this.height = height;
}
// take care of inheritance
var F = function () {};
F.prototype = TwoDShape.prototype;
Triangle.prototype = new F();
Triangle.prototype.constructor = Triangle;
Triangle.uber = TwoDShape.prototype;
// augment prototype
Triangle.prototype.name = 'Triangle';
Triangle.prototype.getArea = function () {
return this.side * this.height / 2;
}
var my = new Triangle(5, 10);
my.toString()
输出:"shape,2Dshape,Triangle"