我最近阅读了Dr. Axel Rauschmayer的一篇很好的文章:
http://www.2ality.com/2015/02/es6-classes-final.html
以下代码片段大致描述了从ECMAScript 5的角度来看ECMAScript 6原型链是如何工作的(原始文章的第4.2节):
// 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');
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);
Thank you all in advance.
Object.setPrototypeOf(...)
相同,它会分配内部的[[Prototype]]
属性。引擎将直接修改该属性,而无需在 JavaScript 中使用setPrototypeOf()
表示该步骤。 - Jonathan LonowskisetPrototypeOf
,它只是一个引入的方法来标准化已弃用的非标准__proto__
特性,出于性能原因,不建议使用它。 - the8472Object.setPrototypeOf(ColorPoint, Point);
负责继承 静态 方法。 - Felix Kling