I'd like to make a python-style getattr
function for a class that I'm writing, so that it can respond to a request for some attribute and react accordingly. I know that you can write a custom "getter" for a property using Object.defineProperty
:
var foo = {bar: 1, baz: 2}
Object.defineProperty(foo, 'qux',
{
get: function(){
console.log('you asked for qux!');
return 5;
}
});
foo.qux // prints 'you asked for qux!', returns 5
I'm wondering though, is there a way to do this for an arbitrary key, so that you can do some logic based on what they asked for? For example
Object.defineGetter(foo, function(key) {
console.log('ah, you asked for ' + key);
if (key[0] === 'a') {
return 0;
} else {
return 1;
}
foo.apple // prints 'ah, you asked for apple', returns 0
foo.orange // prints 'ah, you asked for orange', returns 1
Is there any capability like this in JavaScript?