Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Method to determine the type of an object. #103

Closed
robertschaft opened this issue Jan 21, 2011 · 4 comments
Closed

Method to determine the type of an object. #103

robertschaft opened this issue Jan 21, 2011 · 4 comments
Labels

Comments

@robertschaft
Copy link

During my search for a function that is able to tell me the type of an object, I came up with the following idea:
Every object has a constructor (I am not sure about this) obj.constructor.
You can convert the constructor to a string with obj.constructor.toString(). That returns something like "function Date() { [native code] }" for a Date.
To get the string "Date" I use a regex, but perhaps a combination with indexOf and substr perform better.

function typeOfObject(obj) {
    if (typeof(obj) != 'object') return typeof(obj);
    obj.constructor.toString().match(/^function (\w+)\s*\("/)[1];
}

For performance reasons, i store the regex in a static variable. But again, there could be a different implementation.

function typeOfObject(obj) {
    if (typeof(obj) != 'object') return typeof(obj);
    if (typeof(this.regex) == 'undefined' ) this.regex = new RegExp("^function (\\w+)\\s*\\(");
    return this.regex.exec(obj.constructor.toString())[1];
}

Perhaps this idea is useful for you.

@jed
Copy link
Contributor

jed commented Jan 21, 2011

you don't need the RegExp, just obj.constructor.name.

@robertschaft
Copy link
Author

Nice :)
According to Mozilla Developer .name is Non-Standard.

@ghost
Copy link

ghost commented Jan 21, 2011

Unfortunately, both function decompilation and the name property of functions are non-standard. You can, however, check an object's internal [[Class]] name using Object#toString(). This works for all native JavaScript objects.

var toString = Object.prototype.toString;

toString.call([]); // => "[object Array]"
toString.call(/foo/); // => "[object RegExp]"
toString.call(5); // => "[object Number]"
toString.call(true); // => "[object Boolean]"
toString.call(function(){}); // => "[object Function]"
toString.call("string"); // => "[object String]"
toString.call(new Date()); // => "[object Date]"

@ghost
Copy link

ghost commented Jan 21, 2011

This blog post explains in greater detail how Object#toString() works.

This issue was closed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants