我最近看到了阿克塞尔·劳施梅耶博士写的这篇伟大的文章
http://www.2ality.com/2015/02/es6-classes-final.html
下面的片段大致描述了ECMAScript 6原型链是如何从ECMAScript 5的角度来工作的(原始文章的第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);先谢谢大家。
发布于 2015-06-02 15:32:19
ES5透视图中的“底层视图”不包括这些行--它隐藏在...部分中。这段代码的目的是解释与ES5继承的区别,这与this初始化、new.target、super行为和从其他构造函数继承的构造函数有关。
原型的基本ES5继承仍然存在,并且工作方式与往常一样:
ColorPoint.prototype = Object.create(Point.prototype, {
constructor: {value:ColorPoint, writable:true, enumerable:false, configurable:true}
});
// ... further method definitionshttps://stackoverflow.com/questions/30599857
复制相似问题