我想弄清楚下面的代码是如何工作的。当有人说“创建指向父母原型对象的超级属性”时,有人可以解释它的意思吗?当它说“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"
答案 0 :(得分:1)
在Javascript继承中,不支持访问super
方法,所以我在这里看到的是uber,可以访问其父方法。
将其命名为parent,如下所示:
TwoDShape.parent = Shape.prototype
这样您就可以直接访问父属性:TwoDShape.parent.name
应该返回'shape'
。
toString()
实际上在这里做的是:
var result = []; //declare an array
if (this.constructor.parent) { //if there is a parent prototype
result[0] = this.constructor.parent.toString(); //set the 0 position of result with the return value of parent's toString() method.
}
result[result.length] = this.name; //set the position (0 or 1, if we had a parent it will be 1, otherwise 0) with the current name.
return result.join(', '); //return the names joined with a comma
请注意,我将uber
更改为parent
,因此更具可读性。第一个结果分配将始终为0,因此无需调用result.length
。
每个对象的回叫是什么?:
Shape.toString();
:'shape'
(没有父母)
TwoDShape.toString();
:'shape, 2D shape'
{'shape'
致电Shape.toString();
,'2D shape'
代表自己的名字加入。)
Triangle.toString();
:'shape, 2D shape, Triangle'
{'shape, 2D shape'
号码呼吁TwoDShape.toString();
,'Triangle'
宣传自己的名字,加入)。