Problem
I recently wrote some JavaScript program that includes the use of getters and setters . I read the MDN documentation for both methods, but I got confused trying to use them.
In a nutshell, I just want to create a series of similar properties that will have the same getters and setters , but I do not want to rewrite each setter and getter for each property.
Implementation
The above, I tried to execute the following code:
var defaultProperty = { set: function(val) { this.value = val - 1;
Then I assigned new values ββto my foo and bar properties, for example:
myObj.foo = 3; myObj.bar = 7;
And finally, I was expecting something like this :
console.log(myObj.foo, myObj.bar); > 3 7
But I unexpectedly got this instead :
> 7 7
It seems that both properties apply to either the same memory address or the same setters / receivers. Noticed this, I tried to solve the problem and created each property separately, for example:
Object.defineProperties(myObj, { foo: { set: function(val) { this.value = val - 1; }, get: function() { return this.value + 1; } }, bar: { set: function(val) { this.value = val - 1; }, get: function() { return this.value + 1; } } });
But the result was the same:
myObj.foo = 3; myObj.bar = 7; console.log(myObj.foo, myObj.bar); > 7 7
I also tried using the __defineSetter__ and __defineGetter__ , but the result did not change.
My questions
Now, after several unsuccessful attempts to solve my problems, I wonder:
- Is it possible to define the same setters and getters for different properties of an object?
- If so, what am I doing wrong, and why do my properties behave as if they are the same property?
- Is there a better way to accomplish what I'm trying to do (perhaps without writing each setter and getter for each property)?