Search code examples
javascriptgetter-setter

Define get/set in constructor function


This can be done:

var o = {
  _foo : "bar",
  get Foo() { return _foo; },
  set Foo(value) { _foo = value; }
};

But my code is defined in a constructor function, so I want something like this:

function Something(defaultFoo) {
  var _foo = defaultFoo;
  get Foo() { return _foo; };               // invalid syntax
  set Foo(value) { _foo = value; };         // invalid syntax
}

var something = new Something("bar");
console.log(something.Foo);

That syntax is invalid. Is there some variation that works?


Solution

  • You could use the prototype property and assign the setter and getter.

    BTW, you need to use _foo as property, not as local variable.

    function Something(defaultFoo) {
        this._foo = defaultFoo;
    }
    
    Object.defineProperty(Something.prototype, 'foo', {
        get: function() {
            return this._foo;
        },
        set: function(value) {
            this._foo = value;
        }
    });
    
    var something = new Something("bar");
    console.log(something.foo);
    something.foo = 'baz';
    console.log(something.foo);