3

Is it possible to create property getter/setter as a function?

Standard getter/setter work like following:

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 would need following:

let instance = new Test();
instance.prop('Bar') = 'Foo'; // access setter as a function of prop
console.log(instance.prop('Bar')); // = Foo

Yes, I know it's unorthodox usage and yes, I know that I could implement this functionality bit differently. I'm just interested if this is possible in JS/TS/ES6.

Update

This is the closest I got:

class Test {
  something: any;

  prop(area /* my custom symbol type */) {
    const obj: any = {};
    Object.defineProperty(obj, 'value', {
      // get child object of my complex object
      get: () => this.something[area];
      // replace 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

So in short, I'd like to get rid of value suffix if possible.

Miroslav Jonas
  • 5,407
  • 1
  • 27
  • 41
  • 4
    Since syntactically you *cannot* assign to a function call… no. – deceze Sep 29 '17 at 14:24
  • 4
    Perhaps you just want `instance['Bar'] = 'Foo'`? – deceze Sep 29 '17 at 14:24
  • Possible duplicate of [ES6 getter/setter with arrow function](https://stackoverflow.com/questions/33827519/es6-getter-setter-with-arrow-function) – Daniel Mizerski Sep 29 '17 at 14:27
  • Looks confusing... at least it has to be `instance.prop('Foo')` as a setter, `instance.prop()` - getter – FieryCat Sep 29 '17 at 14:28
  • 1
    Another way of doing this, similar to what FieryCat is saying, would be `instance.prop('Bar', 'Foo')` to set and `instance.prop('Bar')` to get. – Mike Cluck Sep 29 '17 at 14:29
  • @deceze: What I want is a getter function that takes an argument to say pre-filter or reduce the result. Of course this would be possible with getting everything first and filtering later. I was just wondering whether it could be possible to hide it behind a getter/setter. – Miroslav Jonas Sep 29 '17 at 14:47
  • @DanielMizerski: Unfortunately not – Miroslav Jonas Sep 29 '17 at 15:00
  • 1
    @MikeC, as mentioned my question was not how to do it differently, but rather is it possible to solve it this way. – Miroslav Jonas Sep 29 '17 at 15:02
  • 1
    @MiroslavJonas I know but as deceze said, what you want is not possible. I was merely presenting something that *is* possible. – Mike Cluck Sep 29 '17 at 15:12

1 Answers1

0

As @deceze mentioned in the first comment, it is not possible to assign to function call, so solution in the update is as best as it gets.

Miroslav Jonas
  • 5,407
  • 1
  • 27
  • 41