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?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With