0

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.

mrkmg
  • 241
  • 4
  • 14

4 Answers4

2

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') );

Fiddle: http://jsfiddle.net/maniator/T2gWx/

Naftali
  • 144,921
  • 39
  • 244
  • 303
2

This is impossible with the current JavaScript implementations. There is not any kind of default getter as you have in ObjC or other languages.

Adilson de Almeida Jr
  • 2,761
  • 21
  • 37
1

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 );
Dhwanit
  • 610
  • 1
  • 9
  • 17
0

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.

Jamund Ferguson
  • 16,721
  • 3
  • 42
  • 50