Get the name of the requested subobject javascript

别来无恙 提交于 2020-01-06 20:38:01

问题


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

回答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



回答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"


来源:https://stackoverflow.com/questions/24344770/get-the-name-of-the-requested-subobject-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!