I need to make it so that every time a specific property on my object is changed - it will call a special method on the same object.
Example:
MyObject.prototype = Object.create({
specialMethod: function() { /* ... */ }
}, {
someValue: {
set: function(value) {
/* HOW DO I ASSIGN THE VALUE TO MyObject HERE?*/
/* I can't do: this.someValue=value, that would create endless recursion */
this.specialMethod();
}
}
});
How do I assign the value to MyObject within the property setter?
I need to make it so that every time a specific property on my object is changed - it will call a special method on the same object.
Example:
MyObject.prototype = Object.create({
specialMethod: function() { /* ... */ }
}, {
someValue: {
set: function(value) {
/* HOW DO I ASSIGN THE VALUE TO MyObject HERE?*/
/* I can't do: this.someValue=value, that would create endless recursion */
this.specialMethod();
}
}
});
How do I assign the value to MyObject within the property setter?
Share Improve this question edited Sep 23, 2014 at 15:08 YemSalat asked Sep 23, 2014 at 14:56 YemSalatYemSalat 21.6k13 gold badges48 silver badges51 bronze badges 13-
Assigning
MyObject
would ruin all that. You could theoretically doMyObject = value
, but as i said, that destroys the prototype. – Scimonster Commented Sep 23, 2014 at 14:58 -
Why would you want to overwrite
MyObject
? – Bergi Commented Sep 23, 2014 at 14:58 -
2
I assume you simply want to assign a property of the current
MyObject
instance? Just usethis
as always. – Bergi Commented Sep 23, 2014 at 14:59 -
@Bergi, I can't that would create an endless recursion, cause assigning
this.someValue
calls the setter – YemSalat Commented Sep 23, 2014 at 15:00 -
1
@YemSalat: You didn't tell us which property you wanted to assign to.
this.MyValue = value
would work flawlessly… – Bergi Commented Sep 23, 2014 at 15:03
1 Answer
Reset to default 6There is no storage place in a getter/setter property, you cannot store values on it. You need to store it somewhere else and create a getter for that. Two solutions:
Use a second, "hidden" property:
MyObject.prototype.specialMethod: function() { /* ... */ }; Object.defineProperty(MyObject.prototype, "someValue", { set: function(value) { this._someValue = value; this.specialMethod(); }, get: function() { return this._someValue; } });
Use a closure variable (typically created on construction of the instance):
function MyObject() { var value; Object.defineProperty(this, "someValue", { set: function(v) { value = v; this.specialMethod(); }, get: function() { return value; } }); } MyObject.prototype.specialMethod: function() { /* ... */ };