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)?
-
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– user15891882018-01-09 23:30:46 +00:00Commented Jan 9, 2018 at 23:30
Add a comment
|
1 Answer
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
5 Comments
user1589188
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?"
Günter Zöchbauer
I 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.user1589188
Thanks. So having
get square() and new MyClass().square is the same as square() and new MyClass().square()?Günter Zöchbauer
yes, whether
() are required or not is the only differenceuser1589188
Thanks again. If you can add the info above in the comment to the answer I can pick yours as the accepted answer.