Skip to content

Instantly share code, notes, and snippets.

@cnayan
Created December 7, 2017 11:13
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 cnayan/b224eb462ee2aa6218c6f7e6137c1c93 to your computer and use it in GitHub Desktop.
Save cnayan/b224eb462ee2aa6218c6f7e6137c1c93 to your computer and use it in GitHub Desktop.
"Is a" type check in complex object's hierarchy
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");
}
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