Can property getter/setter be implemented as a function?
Traditional getter/setters work like this:
class Test {
something: any;
get prop() {
return something;
}
set prop(value) {
something = value;
}
}
let instance = new Test();
instance.prop = 'Foo';
console.log(instance.prop); // = Foo
I am looking for the following functionality:
let instance = new Test();
instance.prop('Bar') = 'Foo'; // accessing setter as a function of prop
console.log(instance.prop('Bar')); // = Foo
I understand that this is not a common usage and there are other ways to achieve similar results. I am just curious if this can be done in JS/TS/ES6.
Update
This is the closest solution I could find:
class Test {
something: any;
prop(area /* my custom symbol type */) {
const obj: any = {};
Object.defineProperty(obj, 'value', {
// retrieve child object of my complex object
get: () => this.something[area];
// update part of my complex object
set: (value) => {
this.something = {...this.something, [area]: value}
}
});
}
}
let instance = new Test();
instance.prop('Bar').value = 'Foo';
console.log(instance.prop('Bar').value); // = Foo
In summary, I would like to eliminate the need for the suffix value
if possible.