7

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)?

1
  • 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. Commented Jan 9, 2018 at 23:30

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

5 Comments

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?"
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.
Thanks. So having get square() and new MyClass().square is the same as square() and new MyClass().square()?
yes, whether () are required or not is the only difference
Thanks again. If you can add the info above in the comment to the answer I can pick yours as the accepted answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.