Is it possible to call getter and setter from within own class ? If yes what’s the valid syntax instead of invalid
JavaScript
x
2
1
this.gettext();
2
in below class :
JavaScript
1
20
20
1
class Test {
2
3
_text: string;
4
constructor(value: string) {
5
this._text = value;
6
}
7
8
get text() {
9
return this._text;
10
}
11
12
set text(value) {
13
this._text = value;
14
}
15
16
test () {
17
return this.gettext();
18
}
19
}
20
Advertisement
Answer
Setters are called during asignment and getters during reading.
JavaScript
1
2
1
this.text = "testing..."
2
will call the setter passing “testing…” as a value.
JavaScript
1
2
1
console.log(this.text)
2
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:
JavaScript
1
4
1
test() {
2
return this.text;
3
}
4