最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Define getset in constructor function - Stack Overflow

programmeradmin0浏览0评论

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?

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?

Share Improve this question edited May 27, 2017 at 9:47 grokky asked May 27, 2017 at 9:04 grokkygrokky 9,26522 gold badges67 silver badges102 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 9

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);

You could combine both ideas with Object.defineProperty:

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

Make sure however to reference _foo consistently like that, not as this._foo, since you never defined that.

Alternatively, with ES6 class notation (together with private fields added since ES2020), you can do this -- and here I stored the value in the private #foo field:

class Something {
    #foo
    constructor(defaultFoo) {
        this.#foo = defaultFoo;
    }
    get Foo() { return this.#foo; }
    set Foo(value) { this.#foo = value; }
}
发布评论

评论列表(0)

  1. 暂无评论