0

Is it possible to call getter and setter from within own class ? If yes what's the valid syntax instead of invalid

  this.gettext();

in below class :

  class Test {

    _text: string;
    constructor(value: string) {
      this._text = value;
    }

    get text() {
      return this._text;
    }

    set text(value) {
      this._text = value;
    }

    test () {
      return this.gettext();
    }
  }
Alexander Vega
  • 321
  • 1
  • 10
user310291
  • 35,095
  • 76
  • 252
  • 458
  • 2
    `return this.text`. Getters and setters are used like normal properties (not functions) – evolutionxbox May 06 '22 at 22:34
  • 2
    As a side-note, JS classes now support true private fields using the hash symbol `#text: string`, rather than having to rely on underscore hints. – lawrence-witt May 06 '22 at 22:38
  • 1
    Does this answer your question? [How to use getters and setters in Javascript](https://stackoverflow.com/questions/17151298/how-to-use-getters-and-setters-in-javascript) – Heretic Monkey May 06 '22 at 22:43

2 Answers2

1

Setters are called during asignment and getters during reading.

  this.text = "testing..."

will call the setter passing "testing..." as a value.

  console.log(this.text)

will call the getter

If you need to treat as a callable method, wrap it inside a method or don't use properties (getters/setters), use a method instead. If, as you show, you want to wrap it in another method for some reason:

test() {
   return this.text;
}
Alexander Vega
  • 321
  • 1
  • 10
-1
test () {
   return this.text;
}
  • 4
    This is a correct answer, although it would greatly benefit from an explanation. – amn May 07 '22 at 19:21