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.

1

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

Comments

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/

Comments

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

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.