0

I'm trying to create a getter on the following:

function Field(val){
    this.value = {};
}

Field.prototype = {
    get value(){
        return this._value;
    },
    set value(val){
        this._value = val;
    }
};

But what I was able to achieve is a getter for field.value

I want to achieve something like this:

field.value.foo['20'] = 'some_value'; // ==> Setter
field.value.foo['20']; // 'some_value' ==> Getter

But I was not able to achieve this, using the above code .. Can someone help ..

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
user3216499
  • 45
  • 1
  • 3

2 Answers2

1

What you want is a generic getter/setter, able to change any property of your value object.

Unfortunately, this isn't possible with the current version of ECMAScript, you'll have to wait for proxies which should be available with ECMAScript 6 (and are available in the last gecko).

See ES6 wiki for direct proxies.

In the meanwhile, there's probably a solution with the current state of JavaScript for your real problem.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • Can you please shed some light, on "solution with the current state of JavaScript" ? – user3216499 Jan 20 '14 at 19:57
  • @user3216499 "for your real problem". I mean : what you precisely ask for isn't possible in most browsers yet, so you need to start from **why** do you want to do this and look for another design. – Denys Séguret Jan 20 '14 at 19:57
0

You can actually solve this in ES5. I'm documenting this here, for other users to help gain from it..

function Foo() {
    this.__value__ = {};
    this.__value__['20'] = 'some_value';
};

Foo.prototype.__defineGetter__('foo', function() {
    return this.__value__;
});

function Field() {
    this.__value__ = new Foo();
};

Field.prototype.__defineGetter__('value', function() {
    return this.__value__;
});

Now, to test this ..

var field = new Field();
var value = field.value.foo['20'];
console.log(value);

I've updated a JSFiddle here

r8k
  • 88
  • 1
  • 3
  • 1
    Don't use this ! You forgot [the big warning from the MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineGetter) : *Non-standard This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.* – Denys Séguret Jan 22 '14 at 09:58