Skip to content Skip to sidebar Skip to footer

Get The Name Of The Requested Subobject Javascript

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) {

Solution 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

Solution 2:

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"

Post a Comment for "Get The Name Of The Requested Subobject Javascript"