ECMAScript 6 中的原型链

Prototype chains in ECMAScript 6

我最近遇到了 博士的这位伟大的 post。阿克塞尔·劳施迈尔:

http://www.2ality.com/2015/02/es6-classes-final.html

以下片段从 ECMAScript 5 的角度粗略描述了 ECMAScript 6 原型链的工作原理(部分4.2原post):

// ECMAScript 6
class Point {
    constructor(x, y) {
        this.x = x;
        this.y = y;
    }
    ···
}

class ColorPoint extends Point {
    constructor(x, y, color) {
        super(x, y);
        this.color = color;
    }
    ···
}

let cp = new ColorPoint(25, 8, 'green');

"Under the hood" 在 ECMAScript 5 中查看:

 // ECMAScript 5
 // Instance is allocated here
function Point(x, y) {
    // Performed before entering this constructor:
    this = Object.create(new.target.prototype);

    this.x = x;
    this.y = y;
}
···

function ColorPoint(x, y, color) {
    // Performed before entering this constructor:
    this = uninitialized;

    this = Reflect.construct(Point, [x, y], new.target); // (A)
        // super(x, y);

    this.color = color;
}
Object.setPrototypeOf(ColorPoint, Point);
···

let cp = Reflect.construct( // (B)
             ColorPoint, [25, 8, 'green'],
             ColorPoint);
    // let cp = new ColorPoint(25, 8, 'green');

虽然在上面的代码中我明白这是有效的:

Object.getPrototypeOf(ColorPoint) === Point  //true

因为这个:

Object.setPrototypeOf(ColorPoint, Point);

我很难理解为什么这也是真的,因为我找不到任何 "ES5" 解释:

Object.getPrototypeOf(ColorPoint.prototype) === Point.prototype   // true

可能少了这样一行..?

Object.setPrototypeOf(ColorPoint.prototype, Point.prototype);

提前谢谢大家。

从 ES5 的角度来看 "under-the-hood view" 不包括这些行 - 它隐藏在 ... 部分中。这段代码的重点是解释与 ES5 继承的差异,这些差异都是关于 this 初始化、new.targetsuper 行为以及从其他构造函数继承的构造函数。

原型的基本 ES5 继承仍然存在,并且像往常一样工作:

ColorPoint.prototype = Object.create(Point.prototype, {
    constructor: {value:ColorPoint, writable:true, enumerable:false, configurable:true}
});
// ... further method definitions