I find that I can write get methods with or without the "get" keyword in front of the method name. The readings so far suggest that this is for getting property value so you do not need to call the get method but directly use the property name instead? But why does that matter if the property is public already? And how does the program know this method is for which property? Finally, does the "get" keyword do anything on other methods (i.e. methods not binding to any property)?
Asked
Active
Viewed 1,300 times
7
-
Good pointing to a related question, some side info for me, thank you. But it did not answer my questions. "why does that matter if the property is public already?" "how does the program know this method is for which property?" "does the "get" keyword do anything on other methods?" all these were not answered in the related question. – user1589188 Jan 09 '18 at 23:30
1 Answers
6
You can access it like a field
class MyClass {
private _with:number = 5;
private _height:number = 3;
get square() {
return this._with * this._height;
}
}
console.log(new MyClass().square);
15
A getter can be public, protected, or private. It's just cosmetic to make something behave like a property (look like a field) or a function.
The main difference is usually that a function communicates that some actual work will be done, while a property usually is supposed to be cheap and that a getter is not supposed to modify the state, but that are only conventions.
Your example from the comments
So having get square()
and new MyClass().square
is the same as square()
and new MyClass().square()
Answer: yes

Günter Zöchbauer
- 623,577
- 216
- 2,003
- 1,567
-
Thank you. But could you please address my questions? "why does that matter if the property is public already?" "how does the program know this method is for which property?" "does the "get" keyword do anything on other methods?" – user1589188 Jan 09 '18 at 23:31
-
1I don't underszand what's unclear. `public` and `get` ate not related. A getter can ba puböic, protected, or private. It's just cosmetic if you want to make something a propery (look lieke a field) or a function. The main difference is usually that a function communicates that some actual work will be done while a property usually is supposed to be cheap and that a getter is not supposed to modify the state, but that are only conventions. – Günter Zöchbauer Jan 10 '18 at 04:00
-
Thanks. So having `get square()` and `new MyClass().square` is the same as `square()` and `new MyClass().square()`? – user1589188 Jan 10 '18 at 07:26
-
1
-
1Thanks again. If you can add the info above in the comment to the answer I can pick yours as the accepted answer. – user1589188 Jan 10 '18 at 21:07