Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call getter and setter from within a javascript class

Tags:

javascript

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();
    }
  }
like image 679
user310291 Avatar asked Nov 02 '25 13:11

user310291


1 Answers

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;
}
like image 142
UXK Avatar answered Nov 04 '25 04:11

UXK



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!