Skip to content

Instantly share code, notes, and snippets.

@rjvdw
Last active October 19, 2024 10:13
Show Gist options
  • Save rjvdw/1d43242f46af12634e179b0b6bd40f62 to your computer and use it in GitHub Desktop.
Save rjvdw/1d43242f46af12634e179b0b6bd40f62 to your computer and use it in GitHub Desktop.
'use strict'
function F1() {
console.log('construct F1')
this.name = 'F1'
this.f1 = true
}
// does not call the constructor of F1, works with instanceof
function F2() {
console.log('construct F2')
this.name = 'F2'
this.f2 = true
}
F2.prototype = F1.prototype
// calls the constructor of F1, does not work with instanceof
function F3() {
console.log('construct F3')
F1.call(this)
this.name = 'F3'
this.f3 = true
}
// calls the constructor of F1, works with instanceof, introduces an additional prototype "layer"
function F4() {
console.log('construct F4')
Object.setPrototypeOf(this, new F1())
this.name = 'F4'
this.f4 = true
}
// calls the constructor of F1, works with instanceof, does not introduce an additional prototype "layer"
function F5() {
console.log('construct F5')
F1.call(this)
this.name = 'F5'
this.f5 = true
}
F5.prototype = F1.prototype
for (const F of [F1, F2, F3, F4, F5]) {
console.log(F)
const f = new F
console.log(' name=%s', f.name)
console.log(' instanceof F1=%s', f instanceof F1)
console.log(' prototype === F1.prototype = %s', Object.getPrototypeOf(f) === F1.prototype)
console.log()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment