I recently came across this great post by Dr. Axel Rauschmayer:
http://www.2ality.com/2015/02/es6-classes-final.html
The following snippet roughly describes how ECMAScript 6 prototype chains work from an ECMAScript 5 point of view (section 4.2 of the original 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" view in 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');
While in the code above I understand that this is valid:
Object.getPrototypeOf(ColorPoint) === Point //true
because of this:
Object.setPrototypeOf(ColorPoint, Point);
I'm struggling to understand why this is also true since I can't find any "ES5" explanation:
Object.getPrototypeOf(ColorPoint.prototype) === Point.prototype // true
Maybe a line like this is missing..?
Object.setPrototypeOf(ColorPoint.prototype, Point.prototype);
Thank you all in advance.
That "under-the-hood view" from the ES5 perspective doesn't include those lines - it's hidden in the ... sections. The point of this code is to explain the differences from ES5 inheritance, which are all about this initialisation, new.target, super behaviour, and constructor functions inheriting from other constructor functions.
The basic ES5 inheritance for the prototypes is still in place, and works like it always did:
ColorPoint.prototype = Object.create(Point.prototype, {
constructor: {value:ColorPoint, writable:true, enumerable:false, configurable:true}
});
// ... further method definitions
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With