Created
July 21, 2010 19:04
-
-
Save DmitrySoshnikov/484961 to your computer and use it in GitHub Desktop.
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
/** | |
* by Dmitry A. Soshnikov | |
*/ | |
Object.defineProperty(Object, "essence", { | |
value: function objectEssence(value) { | |
var essence = {kind: Object.prototype.toString.call(value).slice(8, -1)}; | |
// use Object(value) just for shortness, it's less effective | |
// than typeof value == "object" && value !== null || typeof value == "function" | |
essence[value === Object(value) ? "object" : "primitive"] = true; | |
return essence; | |
} | |
}); | |
var info = Object.essence; | |
// numbers | |
info(1); // {primitive: true, kind: "Number"} | |
info(new Number(1)); // {object: true, kind: "Number"} | |
// null, undefined | |
info(null); // {primitive: true, kind: "Null"} | |
info(undefined); // {primitive: true, kind: "Undefined"} | |
// strings | |
info("1"); // {primitive: true, kind: "String"} | |
info(new String("1")); // {object: true, kind: "String"} | |
// regexp | |
info(/(?:)/); // {object: true, kind: "RegExp"} | |
// array | |
info([]); // {object: true, kind: "Array"} | |
// object | |
info({}); // {object: true, kind: "Object"} | |
(function () { | |
info(arguments); // {object: true, kind: "Arguments"} | |
})(); | |
info(function () {}); // {object: true, kind: "Function"} | |
// etc. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Yeah, good catch. Then
typeof
is not needed at all in such test. Although method call forObject
should be slower, then usingtypeof
operator (in theory, however, I didn't check it in implementations).