Last active
September 6, 2023 15:03
-
-
Save zeusdeux/4b21df08c9fe3e533380 to your computer and use it in GitHub Desktop.
ES5 inheritance vs ES6 inheritance
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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 |
Object.getPrototypeOf(D.prototype).constructor.call(this)
can be simplize like this:
D.prototype.constructor.call(this);
It still works well
I use the getPrototypeOf
as prototype
property can be overwritten. It is also the way babel and other transpilers did this before we had native class
syntax in JS engines
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
reassign the constructor of
D.prototype
D.prototype.constructor = D