问题
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