views:

653

answers:

2

I'd like to get at the variable name of class.

var Poop = new Class({ 
    getClassName: function() { 
     return arguments.callee._owner.name;
    } 
});
var a = new Poop();
a.getClassName(); //want 'Poop'

I'm making that will be implemented into other classes, and I'd like to build a SQL query that uses the class name (pluralized) for the table.

I've tried various combinations of the above example to try to get the name, and can't figure it out (if it's even possible considering MooTools class system).

A: 

I don't think this is possible in Javascript, due to the prototype-oriented nature of the language. There are several things you can do to determine whether an object is of an existing class that you know, such as:

if (a.constructor == Poop) {
     alert("This will work, but I don't really want any Poop.");
}

However, that doesn't really work for determining an unknown object's class. There's other prototype things you can do to check for class that involve toString(), but they only work for built-in objects, not custom classes, and this is a drawback of prototyping that's not specific to MooTools.

If you check out the 5th Edition of Javascript, The Definitive Guide, page 174, chapter 9.7, there's a nice discussion on it there. Basically the recommendation is to populate your custom classes with a classname property, and override the default base Object class toString() method to check this property when you're calling it on a custom class.

zombat
+3  A: 

Found a solution. Hash has a keyOf function, which will give me the variable name that holds a value. So I made a Hash of window, and then asked for the key of the class constructor.

var Poop = new Class({
    name: function() {
        var w = $H(window);
        return w.keyOf(this.constructor);
    }
});
var a = new Poop();
a.name(); // returns 'Poop'

This of course works only because I create classes in the global window namespace (as is common with MooTools). If you made classes inside some namespace, then you'd just need to Hash that namespace instead.

Edit: I wrote up about how to use this solution and how to make it work in namespaces automatically, for any MooToolers interested.

seanmonstar