I currently use the following syntax to define a class with getters and setters.
SomeObject = function() {
this._propertyOne = 'test';
}
SomeObject.prototype.__defineGetter__('propertyOne', function() {
return this._propertyOne;
});
SomeObject.prototype.__defineSetter__('propertyOne', function(value) {
this._propertyOne = value;
});
Then I can access the property like this:
var o = new SomeObject();
o.propertyOne = 'test2';
console.log(o.propertyOne);
How can I achieve the same with the non-deprecated defineProperty command or something similiar?
I tried something like this:
Object.defineProperty(SomeObject.prototype, 'propertyOne', {
get: function() {
return this._propertyOne;
}.bind(this),
set: function(value) {
this._propertyOne = value;
}.bind(this)
});
But it doesn’t work.
At the moment you run
Object.defineProperty, thethisvalue is not what you want it to be, butwindow(or the object that you run that snippet from). So this is what actually happens:Remove the
.bind(this)part, and it should work fine.