I don't really know the correct words to describe what I am trying to do, but the functionality is very similar to overriding the __get() function of PHP classes. For example this is what I want to do.
var obj = {
param1:'a',
func1:function(){ return '1';},
catch_all:function(input){
return input;
}
}
//alerts 'a'
alert( obj.param1 );
//alerts '1'
alert( obj.func1() );
//alerts 'anything'
alert( obj.anything );
Basically I want a way to redirect any unused key to a predefined key. I have done some research on this and really didn't know what to search for. Any help is greatly appreciated. Thanks.
-
See also: stackoverflow.com/questions/2266789/…Christian C. Salvadó– Christian C. Salvadó2011年12月08日 22:10:25 +00:00Commented Dec 8, 2011 at 22:10
4 Answers 4
This is impossible with the current JavaScript implementations. There is not any kind of default getter as you have in ObjC or other languages.
Comments
You can make a get function, but aside from that you cannot do what you intend.
A get function:
var obj = {
param1:'a',
func1:function(){ return '1';},
get: function(input){
return this[input] !== undefined ? this[input] : 'ERROR';
}
}
//alerts 'a'
alert( obj.param1 );
//alerts '1'
alert( obj.func1() );
//alerts 'ERROR'
alert( obj.get('anything') );
Comments
Kindly find the changes in the code of get method. It is able to modify the memory value reference by obj's param1.
var obj = {
param1:'a',
func1:function(){ return '1';},
get: function(input){
this.param1 = input;
return input;
}
}
//alerts 'a'
alert( obj.param1 );
//alerts '1'
alert( obj.func1() );
//alerts 'anything'
alert( obj.param1 );
Comments
I think what you want are called harmony proxies.
http://wiki.ecmascript.org/doku.php?id=harmony:proxies&s=proxy
They aren't in JavaScript yet, at least not in any current web browser implementations.