Skip to content

Instantly share code, notes, and snippets.

@projektorius96
Forked from zeusdeux/ES5vsES6.js
Created September 6, 2023 15:03
Show Gist options
  • Save projektorius96/5c204eb6e6363f1f9bdc2d4c245ebf61 to your computer and use it in GitHub Desktop.
Save projektorius96/5c204eb6e6363f1f9bdc2d4c245ebf61 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment