Reputation: 9265
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?
Upvotes: 10
Views: 6875
Reputation: 350252
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; }
}
Upvotes: 7
Reputation: 386568
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);
Upvotes: 9