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.
Use the constructor property. Example for the Array class (works with
any class):
var arr = new Array('A', 'B');
alert(arr.constructor.name);
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
"ted" <tedNOSP...@yahoo.com> wrote in message
news:abkssd$2h2$1...@slb6.atl.mindspring.net...
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