Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getters & Setters in a prototype pattern

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

like image 366
Skyler Avatar asked Feb 10 '26 21:02

Skyler


1 Answers

Why not do it on the prototype itself?

function Person(name){
    this._name = name;
}

Object.defineProperty( Person.prototype, 'name', {
    get:function(){ return this._name; }
})
like image 60
jusopi Avatar answered Feb 12 '26 14:02

jusopi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!