Define get / set in constructor function

It can be done:

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

But my code is defined in the 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);

This syntax is invalid. Is there any variation that works?

+4
source share
2 answers

You can use the prototype property and assign an installer and getter.

By the way, you need to use the property _fooas a property, and not as a 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);
Run codeHide result
+5
source

You could combine both ideas with Object.assign:

function Something(defaultFoo) {
  var _foo = defaultFoo;
  Object.assign(this, {
      get Foo() { return _foo; },
      set Foo(value) { _foo = value; }
  });
}

Make sure, however, that the link _foois the same as this, and not how this._foo, since you never defined it.

, ES6, - this._foo:

class Something {
    constructor(defaultFoo) {
        this._foo = defaultFoo;
    }
    get Foo() { return this._foo; }
    set Foo(value) { this._foo = value; }
}
+1

Source: https://habr.com/ru/post/1678022/


All Articles