0

If I have an object with an anonymous function inside how do I know what subobject is being requested so that I can return a value?

var obj = function(a) {
    switch (a) {
        case 'subprop1': return 'subval1';
        case 'subprop2': return 'subval2';
        case 'subprop3': return 'subval3';
        default: return 'defaultval'; 
    }
}

So if I call:

obj.subprop1

I should get:

subval1
godismyjudge95
  • 922
  • 1
  • 9
  • 15
  • I believe something like default getter (in case you mean objects, not functions like in the snippet you posted) would solve your issue, but apparently there is no such thing, you can read more here http://stackoverflow.com/questions/3112793/how-can-i-define-a-default-getter-and-setter-using-ecmascript-5 – kaapa Jun 21 '14 at 18:52

2 Answers2

1

This is not really possible with plain objects unless your environment supports Proxy.

In this case it would be quite easy (haven't tested):

var obj = function(a) {
    switch (a) {
        case 'subprop1': return 'subval1';
        case 'subprop2': return 'subval2';
        case 'subprop3': return 'subval3';
        default: return 'defaultval'; 
    }
};

var objProxy = new Proxy(obj, {
    get: function (target, name) { return target(name); }
});

objProxy.subprop1; //should return subval1
objProxy.nonExisting; //shoud return defaultval
plalx
  • 42,889
  • 6
  • 74
  • 90
-1

Call obj("subprop1");

obj is defined as the function, thus you would call it like a declared function (this is called a named function expression).

If you wanted to do obj.subprop1 you would need to define obj as an object like so

obj = {
    subprop1: 'subval1',
    subprop2: 'subval2',
    ...
};
console.log(obj.subprop1); //Spits out "subval1"
Kodlee Yin
  • 1,089
  • 5
  • 10