Skip to content

Instantly share code, notes, and snippets.

@mutoo
Created July 23, 2020 23:56
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 mutoo/dca6326a8928b35eff4d57983a726b94 to your computer and use it in GitHub Desktop.
Save mutoo/dca6326a8928b35eff4d57983a726b94 to your computer and use it in GitHub Desktop.
the instanceOf function that works with primitive type.
function instanceOf(inst, cls) {
if (inst === null || inst === undefined)
return false;
if (typeof cls !== 'function')
throw new TypeError("Second parameter is not a constructor");
let instance = inst;
while (instance.__proto__) {
if (instance.__proto__ === cls.prototype) {
return true;
}
instance = instance.__proto__;
}
return false;
}
1 instanceof Number; // false;
" " instanceof String; // false;
instanceOf(1, Number); // true
instanceOf(' ', String) // true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment