views:

36

answers:

1

Hi,

is it possible to decide at runtime which properties of a JS object should be enumerated?

Something like

myobj = {};
myobj.keys = function() {  // I made this keys function up. Is there something like that in JS?
  if ((new Date).getSeconds() < 30)
    return [1,2,3];
  else
    return [4,5,6];
}

for(p in myobj)
  console.log(p); // returns either 1,2,3 or 4,5,6

Furthermore, is it possible to call a function if a object's property does not exist? Something like

myobj.fallbackFunction = function(arg) { return arg; };
console.log( myobj['nonexisting-property'] ); // returns the string 'nonexisting-property'

And my final question: Is it possible to call an object as a function? Like

myobj.call = function(arg) { console.log(arg) };
myobj(123)  // returns 123` 

Sorry, I've had a look at Qt's QScriptEngine where you can do stuff like that, but I don't know how to implement this in native JS...

Cheers, Manuel

+1  A: 

It's possible to control which properties of an object are enumerated using Object.defineProperty in ECMAScript 5, which is currently making its way into browsers:

var o = { "foo": 1, "bar": 2 };

for (var i in o) { console.log(i); } // Logs "foo" and "bar";

Object.defineProperty(o, "foo", { enumerable: false });

for (var i in o) { console.log(i); } // Logs just "bar";

For the next part, there's no standardized or cross-browser way to call a method if a property of an object is undefined.

Finally, you can't make any old object callable as a function, but you could just define your variable as a function in the first place and it will have all the usual features of an object, since functions are themselves objects (Function.prototype inherits from Object.prototype). For example, you can assign properties to functions:

var f = function() { alert("Hello"); };
f.myProp = 1;
Tim Down