Twerterus Twerterus - 1 year ago 89
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?)

Answer Source

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;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download