Last active
July 27, 2022 22:52
-
-
Save derhuerst/b1555f627de630a0f9f3d475fb3016cf to your computer and use it in GitHub Desktop.
JavaScript: calling the grandparent's constructor
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
// Note: You wouldn't ever want to do this! | |
function A () { | |
this.a = true | |
return this | |
} | |
A.prototype.fromA = 'from A' | |
function B () { | |
this.constructor.prototype.__proto__.constructor.call(this) | |
this.b = true | |
return this | |
} | |
B.prototype = Object.create(A.prototype) | |
B.prototype.constructor = B | |
B.prototype.fromB = 'from B' | |
function C () { | |
// By using __proto__.__proto__, we're skipping B: | |
this.constructor.prototype.__proto__.__proto__.constructor.call(this) | |
this.c = true | |
return this | |
} | |
C.prototype = Object.create(B.prototype) | |
C.prototype.constructor = C | |
C.prototype.fromC = 'from C' | |
new C() | |
// C { a: true, c: true } | |
(new C()).fromB | |
// 'from B' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment