views:

612

answers:

4

Long story short: I'm in a situation where I'd like a PHP-style getter, but in JavaScript.

My JavaScript is running in Firefox only, so Mozilla specific JS is OK by me.

The only way I can find to make a JS getter requires specifying its name, but I'd like to define a getter for all possible names. I'm not sure if this is possible, but I'd very much like to know.

A: 

You could use a for in statement:

var myObject = { some: 'data', other: 'stuff' };
for(o in myObject) {
  alert(o);
}
Slace
A: 

If you're looking for something like PHP's __get() function, I don't think Javascript provides any such construct.

The best I can think of doing is looping through the object's non-function members and then creating a corresponding "getXYZ()" function for each.

In dodgy pseudo-ish code:

for (o in this) {
    if (this.hasOwnProperty(o)) {
        this['get_' + o] = function() {
            // return this.o -- but you'll need to create a closure to
            // keep the correct reference to "o"
        };
    }
}
nickf
+2  A: 

Javascript 1.5 does have getter/setter syntactic sugar. It's explained very well by John Resig here

It's not generic enough for web use, but certainly Firefox has them (also Rhino, if you ever want to use it on the server side).

Javier
+6  A: 

The closest you can find is __noSuchMethod__, which is JavaScript's equivalent of PHP's __call().

Unfortunately, there's no equivalent of __get/__set, which is a shame, because with them we could have implemented __noSuchMethod__, but I don't yet see a way to implement properties (as in C#) using __noSuchMethod__.

var foo = {
    __noSuchMethod__ : function(id, args) {
        alert(id);
        alert(args);
    }
};

foo.bar(1, 2);
Ionuț G. Stan
I was actually trying to create a "message eating nil" equivalent, and this does it *exactly*! Thanks!
arantius
I had no idea about the "message eating nil" concept. Thanks
Ionuț G. Stan