Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 932
grokky Avatar asked May 27 '17 09:05

grokky


1 Answers

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);
like image 70
Nina Scholz Avatar answered Sep 28 '22 14:09

Nina Scholz