Last active
August 29, 2015 14:16
-
-
Save pedrosancao/680b02d1ffe8cb90ee7a to your computer and use it in GitHub Desktop.
A improved type verification function that avoid problems with instanceof and typeof, works with literals and across frames for JavaScript natives objects only
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
/** | |
* A improved type verification function that avoid problems with instanceof and typeof, works with literals and across frames | |
* for JavaScript natives objects only | |
* | |
* @author Pedro Sanção <dev at sancao dot co> | |
* @license GNU GPL v2 | |
* | |
* @see http://stackoverflow.com/questions/203739/why-does-instanceof-return-false-for-some-literals?rq=1 | |
* @see http://stackoverflow.com/questions/14391506/instanceof-operator-fails-when-passing-an-object-through-windows | |
*/ | |
function isType(value, object) { | |
return Object.prototype.toString.call(value) === '[object ' + object.name + ']'; | |
} | |
isType([], Array); // true | |
isType([], Object); // false | |
isType({}, Object); // true | |
isType('', String); // true | |
isType(false, Boolean); // true | |
isType('', Boolean); // false | |
isType(document.createElement('div'), HTMLDivElement); // true | |
// and so on |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment