在构造函数中定义get/set

gro*_*kky 6 javascript getter-setter

这可以做到:

var o = {
  _foo : "bar",
  get Foo() { return _foo; },
  set Foo(value) { _foo = value; }
};
Run Code Online (Sandbox Code Playgroud)

但我的代码是在构造函数中定义的,所以我想要这样的东西:

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);
Run Code Online (Sandbox Code Playgroud)

该语法无效.有一些变化有效吗?

Nin*_*olz 6

您可以使用prototype属性并分配setter和getter.

顺便说一下,你需要使用_foo属性,而不是局部变量.

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 Code Online (Sandbox Code Playgroud)


tri*_*cot 5

您可以将这两个想法与Object.assign

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

但是请确保_foo始终像那样引用,而不是像那样引用this._foo,因为您从未定义过它。

或者,使用 ES6 类表示法,您可以执行此操作 - 在这里我将值存储在this._foo

class Something {
    constructor(defaultFoo) {
        this._foo = defaultFoo;
    }
    get Foo() { return this._foo; }
    set Foo(value) { this._foo = value; }
}
Run Code Online (Sandbox Code Playgroud)