Last active
December 21, 2020 08:23
-
-
Save Buggytheclown/ade9c337fc8869e3a9d3a43b195519c2 to your computer and use it in GitHub Desktop.
simplified version of JS 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
class CA { | |
static staticMethodA() { | |
return 42; | |
} | |
constructor(name = 'default name') { | |
this.name = name; | |
} | |
methodA() { | |
return this.name; | |
} | |
} | |
class CB extends CA { | |
methodB() { | |
return 43; | |
} | |
} | |
function _inherits(subClass, superClass) { | |
// `subClass.prototype =` - subClass instances should provide access to superClass methods | |
// `Object.create` - dont share the same prototype object to prevent modification by reference for both (subClass and superClass) | |
subClass.prototype = Object.create(superClass.prototype); | |
// `constructor` - do not override subClass.prototype.constructor (specification requirements, not many real-world use cases) | |
subClass.prototype.constructor = subClass; | |
// share static methods | |
Object.setPrototypeOf(subClass, superClass); | |
} | |
var CA = (function () { | |
function CA(name = 'default name') { | |
this.name = name; | |
} | |
CA.staticMethodA = function staticMethodA() { | |
return 42; | |
}; | |
CA.prototype.methodA = function methodA() { | |
return this.name; | |
}; | |
return CA; | |
})(); | |
var CB = (function (_CA) { | |
_inherits(CB, _CA); | |
function CB() { | |
// call `super(...args)` if constructor is not defined | |
return _CA.apply(this, arguments) || this; | |
} | |
CB.prototype.methodB = function methodB() { | |
return 43; | |
}; | |
return CB; | |
})(CA); | |
const ca = new CA('my CA'); | |
const cb = new CB(); | |
console.assert(cb instanceof CA, 2); | |
console.assert(cb instanceof CB, 1); | |
console.assert(ca.methodA() === 'my CA', 3); | |
console.assert(cb.methodA() === 'default name', 4); | |
console.assert(ca.methodB === undefined, 5); | |
console.assert(cb.methodB() === 43, 6); | |
console.assert(CA.staticMethodA() === 42, 7); | |
console.assert(CB.staticMethodA() === 42, 8); | |
console.assert(cb.constructor === CB, 9); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment