Last active
December 25, 2015 06:09
-
-
Save chandu-io/6930186 to your computer and use it in GitHub Desktop.
js :: getClassName :: type of object (ECMAScript standard to find the class of Object)
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
| // ECMAScript standard to find the class of Object => Use toString method. | |
| function getClassName(o) { return Object.prototype.toString.call(o).split(' ')[1].slice(0, -1) } | |
| // OR | |
| function getClassName(o) { return Object.prototype.toString.call(o).match(/^\[object\s(.*)\]$/)[1] } | |
| console.log(getClassName([])); // 'Array' | |
| console.log(getClassName({})); // 'Object' | |
| console.log(getClassName('')); // 'String' | |
| console.log(getClassName(0)); // 'Number' | |
| console.log(getClassName(NaN)); // 'Number' | |
| console.log(getClassName(Infinity)); // 'Number' | |
| console.log(getClassName(false)); // 'Boolean' | |
| console.log(getClassName(null)); // 'Null' | |
| console.log(getClassName(undefined)); // 'Undefined' | |
| console.log(getClassName()); // 'Undefined' | |
| console.log(getClassName(new Date())); // 'Date' | |
| console.log(getClassName(/r/)); // 'RegExp' | |
| console.log(getClassName(function () {})); // 'Function' | |
| console.log(getClassName(new Error())); // 'Error' | |
| // Most of the logic is taken from | |
| // http://perfectionkills.com/instanceof-considered-harmful-or-how-to-write-a-robust-isarray/ | |
| // http://www.adobe.com/devnet/html5/articles/object-types-in-javascript.html |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment