Skip to content

Instantly share code, notes, and snippets.

@zeusdeux
Last active September 6, 2023 15:03
Show Gist options
  • Save zeusdeux/4b21df08c9fe3e533380 to your computer and use it in GitHub Desktop.
Save zeusdeux/4b21df08c9fe3e533380 to your computer and use it in GitHub Desktop.
ES5 inheritance vs ES6 inheritance
/* ES6/ES2015 classes */
class A {
constructor() {
this.a = 10
}
print() {
console.log(this.a, this.b)
}
}
class B extends A {
constructor() {
super()
this.b = 20
}
}
/* ES5 equivalent */
function C() {
this.c = 100
}
C.prototype.print = function() {
console.log(this.c, this.d)
}
function D() {
/*
* Same as C.call(this) since we later do D.prototype = Object.create(C.prototype)
*/
Object.getPrototypeOf(D.prototype).constructor.call(this)
this.d = 200
}
D.prototype = Object.create(C.prototype)
let a = new A()
let b = new B()
let c = new C()
let d = new D()
b.print() // outputs 10 20
@marlonry
Copy link

marlonry commented Mar 10, 2021

Object.getPrototypeOf(D.prototype).constructor.call(this) can be simplize like this:

D.prototype.constructor.call(this);

It still works well

I think this throws an error cause you are basically calling Ds constructor not Cs constructor. Maybe explain better how you are getting it to work.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment