Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

How to find Class Name of an object?

0 views
Skip to first unread message

ted

unread,
May 11, 2002, 2:30:39 PM5/11/02
to
How do I get the class name of an object?

For instance if I have object "someObject", how would I find the class that
it belonged to?

Right now I'm just sticking a member variable in the class indicating it's
name. But there's gotta be a better way.

Thanks.


Keith Bowes

unread,
May 11, 2002, 4:10:33 PM5/11/02
to
On 5/11/2002 2:30 PM, ted wrote:
> How do I get the class name of an object?
>
> For instance if I have object "someObject", how would I find the class that
> it belonged to?

Use the constructor property. Example for the Array class (works with
any class):
var arr = new Array('A', 'B');
alert(arr.constructor.name);

ted

unread,
May 12, 2002, 12:59:34 AM5/12/02
to
Keith, thanks for the reply.

I only get 'undefined' when I try using "arr.constructor.name".

But I found that I could use the constructor property to test for equality
like this:
arr.constructor == Array

"Keith Bowes" <do....@spam.me> wrote in message
news:3CDD7AB9...@spam.me...

Dan

unread,
May 12, 2002, 1:21:48 PM5/12/02
to
Use typeof, typeof(someObject) or just typeof someObject, will return
the appropriate type.


Dan

"ted" <tedNOSP...@yahoo.com> wrote in message
news:abkssd$2h2$1...@slb6.atl.mindspring.net...

Grant Wagner

unread,
May 17, 2002, 2:44:36 PM5/17/02
to
typeof() just returns "object" for any object, I believe he wants to know the
*name* of constructor.

I posted code earlier for a specific case, but I decided the following is
better:

<script>
function globalClassOf() {
var re = /function\s+(.+)\s*\(\)\s*\{/;
var result = re.exec(this.constructor);
return (result && result[1] ? result[1] : 'Unknown');
}

Object.prototype.classOf = globalClassOf;


function myClass() {
this.x = 1;
this.y = 2;
}

var a = new myClass();
alert(a.classOf());
var b = new String();
alert(b.classOf());
</script>

With globalClassOf() attached to the Object prototype, all classes decended from
"Object" have a "classOf()" method that returns the name of the constructor
(this includes all custom classes, as well as a few built-in ones as
demonstrated above).

Dan wrote:

--
| Grant Wagner <gwa...@agricoreunited.com>

* Client-side Javascript and Netscape DOM Reference available at:
* http://developer.netscape.com/docs/manuals/javascript.html
* Internet Explorer DOM Reference available at:
* http://msdn.microsoft.com/workshop/author/dhtml/reference/dhtmlrefs.asp
* Tips for upgrading JavaScript for Netscape 6/Mozilla
* http://www.mozilla.org/docs/web-developer/upgrade_2.html


0 new messages