For example, here’s my “Hello” machine:
hello_machine = new HelloMachine;
At this point, if someone tries to access a property in hello_machine, I’d like the following to happen.
hello_machine.fred;
hello_machine.greetings(); // output: Hi, fred!
hello_machine.george;
hello_machine.greetings(); // output: Hi, george!
I’d like this to happen automatically, regardless of the property they are trying to access. I don’t want anything hard-coded.
This is the function that I would like called:
function set_buddy(name) {
buddy = name;
}
And greetings would be the following:
function greetings() {
alert('Hi, ' + buddy);
}
The obvious solution is to not do this. It’s terrible practice and it changes a very fundamental way Javascript behaves. However, I’m in a position where this type of behavior would be fantastic to have.
My gut tells me that this isn’t possible, and the internet has not been able to dissuade me of that fact (my head tells me I’m a fool for asking). But I know that Javascript is a fickle mistress and it would not surprise me if this functionality existed. Therefore, if anyone knows of any hack I can implement to get this behavior, I would surely appreciate it.
Sadly, you cannot do this without proxies: http://soft.vub.ac.be/~tvcutsem/proxies/
Which aren’t widely supported at all yet. Not even close.
If the properties you wish to invoke were known before hand, you could declare getter methods with
Object.define_propertywhich is a bit more widely supported. But without knowing the properties to be invoked ahead of time, there is no way to intercept them without proxies.