Created
July 23, 2020 23:56
-
-
Save mutoo/dca6326a8928b35eff4d57983a726b94 to your computer and use it in GitHub Desktop.
the instanceOf function that works with primitive type.
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
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