I'd like to use getters & setters within a prototype pattern. I did this by putting Object.defineProperty in the constructor.
I know that i can just create getWhatever() methods in the prototype object, by I like the brevity of accessing properties through real getters/setters
But having the defineProperty outside the prototype object like this doesn't feel right to me. Is there a better way?
function Person(name) {
this._name = name;
Object.defineProperty(this, 'name', {
get: function() {
return this._name;
}
});
}
the plunk: https://plnkr.co/edit/h3tgJjQBGspepdho3lqJ?p=preview
Why not do it on the prototype itself?
function Person(name){
this._name = name;
}
Object.defineProperty( Person.prototype, 'name', {
get:function(){ return this._name; }
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With