Search code examples
javascriptprototypegetter-setter

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


Solution

  • Why not do it on the prototype itself?

    function Person(name){
        this._name = name;
    }
    
    Object.defineProperty( Person.prototype, 'name', {
        get:function(){ return this._name; }
    })