Reputation: 45
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 ..
Upvotes: 0
Views: 67
Reputation: 88
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
Upvotes: 0
Reputation: 382168
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.
Upvotes: 1