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)?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With