-
-
Save NicklausBrain/c822b2bedb8cd9a0dd1d6948f55b4bae to your computer and use it in GitHub Desktop.
ES5 inheritance vs ES6 inheritance
This file contains hidden or 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment