TypeScript: use private or public in the constructor

I am new to TypeScript and I have seen examples of this to deal with injected objects and set it to a component property (this.anything)

First with the publication and manual installation of this.nav

export class XPTO {
   constructor(public nav: NavController) {
      this.nav = nav;
   }
}

and this, with private

export class XPTO {
   constructor(private nav: NavController) {
      //this.nav is nav?
   }
}

in both cases, after creating the this.nav object, it is a NavController object. What are the differences between both implementations? Or is it the same when compiled to plain javascript?

+4
source share
2 answers

In fact, in the first example, an explicit assignment is not required at all:

export class XPTO {
   constructor(public nav: NavController) {
       // This line is not required.
       // this.nav = nav;
       this.someFunction();
   }
   someFunction(){
       console.log(this.nav); // Prints out the NavController.
   }
}

, public private , / .

, , , .

javascript , , .

+9

public private, Typescript Typescript. , , JavaScript .

Typescript , , , .

+3

Source: https://habr.com/ru/post/1656636/


All Articles