Skip to content

Instantly share code, notes, and snippets.

@DmitrySoshnikov
Created July 21, 2010 19:04
Show Gist options
  • Save DmitrySoshnikov/484961 to your computer and use it in GitHub Desktop.
Save DmitrySoshnikov/484961 to your computer and use it in GitHub Desktop.
/**
* 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.
@DmitrySoshnikov
Copy link
Author

Yeah, good catch. Then typeof is not needed at all in such test. Although method call for Object should be slower, then using typeof operator (in theory, however, I didn't check it in implementations).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment