I am curious what the difference between these two functions would be in Angular 4:
get currentIndex(): number {
return `Current Index is ${this.index}`;
}
public currentIndex(): number {
return `Current Index is ${this.index}`;
}
Do they do exactly the same thing? If so when would they do something different?
They're pretty much the same, except that functions/methods tend to imply a calculation. So when you're just accessing data (like the index in this case), a function can look odd or seem like overkill.
Using a getter is kind of the best of both worlds. It looks like simple data access - currentIndex
versus currentIndex()
- while allowing you to add logic later if you need to do something like a calculation.
Technically they are different though, and you can use the TypeScript PlayGround to see how they compile down to different code.