Skip to content

Instantly share code, notes, and snippets.

@derhuerst
Last active July 27, 2022 22:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save derhuerst/b1555f627de630a0f9f3d475fb3016cf to your computer and use it in GitHub Desktop.
Save derhuerst/b1555f627de630a0f9f3d475fb3016cf to your computer and use it in GitHub Desktop.
JavaScript: calling the grandparent's constructor
// 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