Twerterus Twerterus - 6 months ago 44
TypeScript Question

Setting a variable global for a class in the constructor Angular 2

I am sure that this has been answered before, so I humbly apologize in advance.

I have noticed that setting a variable private in the constructor allows the rest of the class to use the variable.


constructor(private foo : bar) { }

later in code

My question is simple - why does this work?

(what is angular and typescript doing in the background?)


Because TypeScript is defined this way. Prefixing a constructor parameter with private or public implicitly creates a matching property where the value is assigned. It's just a short form (syntactic sugar) of

private foo:bar;
constructor(foo:bar) { = foo;