As you know we can define getters and setters in JS using defineProperty()
. I\'ve been stuck when trying to extend my class using defineProperty()
.
As you define your properties on the prototype object of all user instances, all those objects will share the same value
variable. If that is not what you want, you will need to call defineFields
on each user instance separately - in the constructor:
function User(id, name){
this.define_fields(["name", "id"]);
this.id = id
this.name = name
}
User.prototype.define_fields = function(fields) {
var user = this;
fields.forEach(function(field_name) {
var value;
Object.defineProperty(user, field_name, {
get: function(){ return value; },
set: function(new_value){
/* some business logic goes here */
value = new_value;
}
});
});
};