Created
December 7, 2017 11:13
-
-
Save cnayan/b224eb462ee2aa6218c6f7e6137c1c93 to your computer and use it in GitHub Desktop.
"Is a" type check in complex object's hierarchy
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
const check = require('./typeCheck'); | |
const Base = () => { | |
console.log("base"); | |
return this; | |
} | |
const Derived = function () { | |
Base.call(this); | |
console.log("derived"); | |
return this; | |
}; | |
Derived.prototype = Object.create(Base); | |
Derived.prototype.constructor = Derived; | |
const d = new Derived(); | |
// code to evaluate | |
if (check.is(d, Base)) { | |
console.log("Instantiated from Base"); | |
} | |
if (check.is(d, Derived)) { | |
console.log("Instantiated from Derived"); | |
} |
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
exports = module.exports = {} | |
// Idea extracted from https://stackoverflow.com/questions/332422/how-do-i-get-the-name-of-an-objects-type-in-javascript | |
exports.is = (o, T) => { | |
return o.constructor.name === T.name; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment