Understanding "public" / "private" in the typescript class

In the type of script below, the code, regardless of whether the name is "public" or "private", the java script code that is generated is the same.

So my question is how to decide when there should be a public or private constructor parameter?

// typescript code
class Animal {  
constructor( public name: string) {     
}

}

// generated JS code
var Animal = (function () {
function Animal(name) {
    this.name = name;
}
return Animal;
}());
+7
source share
3 answers

The generated Java script code is the same

They generate the same JavaScript, but do not have the same semantics as the type.

privatean element can only be accessed inside the class, while it publiccan be Discounted externally.

More

: https://basarat.gitbooks.io/typescript/content/docs/classes.html#access-modifiers.

let foo = 123;

ES5,

const foo = 123; 

let foo = 123;foo = 456 , const foo = 123; foo = 456 const foo = 123; foo = 456 .

+6

, , , , . , .

?

, public private . , protected.

( ) .

, private , .

, , .

TypeScript.

, ?!

, , . , , ! , TypeScript, , .

+4

ESnext hash #:

class MyClass {
  a = 1;          // .a is public
  #b = 2;         // .#b is private
  static #c = 3;  // .#c is private and static
  incB() {
    this.#b++;
  }
}

const m = new MyClass();
m.incB(); // runs OK
m.#b = 0; // error - private property cannot be modified outside class

* : , .

https://github.com/tc39/proposal-private-methods

0

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


All Articles