Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the effect of adding "get" keyword on Angular 2 methods? [duplicate]

Tags:

angular

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

like image 709
user1589188 Avatar asked Jan 09 '18 01:01

user1589188


1 Answers

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

like image 160
Günter Zöchbauer Avatar answered Oct 23 '22 05:10

Günter Zöchbauer