Created
February 7, 2013 17:13
-
-
Save arashmilani/4732488 to your computer and use it in GitHub Desktop.
Trying to find much better way to assert Types in javascript rather than comparing types in string using typeof
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
function assertType(obj, type) { | |
return obj.constructor.name === type.name | |
} | |
console.info(assertType("test", String)); //true | |
console.info(assertType(1, String)); //false | |
console.info(assertType(1, Number)); //true | |
function Book(){}; | |
function Desk(){}; | |
var book = new Book(); | |
console.info(assertType(book, Book)); //true | |
console.info(assertType(book, Desk)); //false | |
console.info(assertType([], Array)); //true | |
console.info(assertType(function(){}, Function)); //true |
console.info(assertType({}, Object)); //True
Note that there's NO WAY to beat "typeof" in performance.
Check it here for yourself: http://jsperf.com/am-type-assertion#run
Geeks, here the updated gist with prototype
: https://gist.github.com/afshinm/4733756
Thank you Afshin for the prototype
version :)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
var testObj=new Object();
console.info(assertType(testObj, Object)); //True