Skip to content

Instantly share code, notes, and snippets.

@pedrosancao
Last active August 29, 2015 14:16
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 pedrosancao/680b02d1ffe8cb90ee7a to your computer and use it in GitHub Desktop.
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
/**
* 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