1

我试图弄清楚下面的代码是如何工作的。有人能解释一下“创建一个指向父原型对象的超级属性”是什么意思吗?当它说“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"

4

1 回答 1

1

在 Javascript 继承中,不支持访问super方法,所以我在 uber 中看到的是可以访问其父方法。
将其命名为父级,如下所示:
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'

于 2012-10-28T01:13:19.323 回答