Twerterus Twerterus - 8 days ago 7
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.

EX:

constructor(private foo : bar) { }

...
later in code
...

this.foo


My question is simple - why does this work?

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

Answer

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) {
  this.foo = foo;
}
Comments