It's prototypes all the way down
I took the time to illustrate the similarities between traditional JavaScript prototypal inheritance using constructor functions to manage inheritance, and the syntax afforded by ES2015 classes. I originally did this to help clear up some incomplete understanding on my team, but I thought that other folks might benefit from seeing this as well.
I'll provide the illustration as preformatted code, but I'll follow that with an image showing the two approaches side-by-side, because I think it's good to see how they compare to each other line-by-line.
I almost always think it's valuable to see where we’ve been, and where we are, so we can look forward to where we're going.
This isn't anything new, but I worry when we start to forget history.
// constructor function
function Klass(data) {
this.data = data;
}
Klass.prototype.getData = function () {
return this.data;
};
Klass.prototype.setData = function(data) {
this.data = data;
};
var klass = new Klass('foo'); // Call "constructor".
klass.getData(); // -> "foo"
klass.setData('bar'); // And so on.
function KlassAddBaz() {}
KlassAddBaz.prototype = new Klass('foo');
KlassAddBaz.prototype.constructor = KlassAddBaz;
KlassAddBaz.prototype.updateData = function () {
this.data = this.data + 'baz';
};
var klassAddBaz = new KlassAddBaz();
klassAddBaz.getData(); // "foo"
klassAddBaz.setData('bar');
klassAddBaz.updateData();
klassAddBaz.getData(); // "barbaz"
// ES2015 class syntax
class Klass {
constructor(data) {
this.data = data;
}
getData() {
return this.data;
}
setData(data) {
this.data = data;
}
}
const klass = new Klass('foo'); // Call "constructor".
klass.getData(); // -> "foo"
klass.setData('bar'); // And so on.
class KlassAddBaz extends Klass {
updateData() {
this.data = this.data + 'baz';
}
}
const klassAddBaz = new KlassAddBaz('foo');
klassAddBaz.getData(); // "foo"
klassAddBaz.setData('bar');
klassAddBaz.updateData();
klassAddBaz.getData(); // "barbaz"
(Click to enlarge.)
![](https://www.jeromecovingto
That's all for now.