Created
October 2, 2020 22:00
-
-
Save toddfast/0cbbbc4639226ef004b96d07aec9f172 to your computer and use it in GitHub Desktop.
A test case for a module-like pattern for inheritance using Object.create(). Useful in older JS versions, requiring just a shim for Object.create().
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
Parent.count = 0; | |
function Parent(val) { | |
var value = val; | |
var index = -1; | |
(function constructor(c) { | |
index = c; | |
})(Parent.count++); | |
function toString() { | |
return value + ":" + index; | |
} | |
var publicInterface = Object.create({},{ | |
inheritedProp: { value: index }, | |
toString: { value: toString } | |
}); | |
return publicInterface; | |
} | |
function Child(val) { | |
var sup = new Parent(val); | |
function toString() { | |
return sup.toString() + " overridden"; | |
} | |
var publicInterface = Object.create(sup,{ | |
toString: { value: toString }, | |
doSomething: { value: function() { console.log("something"); } } | |
}); | |
return publicInterface; | |
} | |
const bar = new Parent("bar"); | |
const baz = new Child("baz"); | |
console.log("bar: ",bar.toString(), bar.inheritedProp, bar); | |
console.log("baz: ",baz.toString(), baz.inheritedProp, baz); | |
console.log(bar.toString === baz.toString); | |
baz.doSomething(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment