class

需要先定义类型才能使用

  1. class Person {
  2. public str: string;
  3. constructor() {
  4. this.str = '公有属性';
  5. }
  6. // 公有方法
  7. public pubFun() {
  8. console.log(this.str);
  9. }
  10. }

public

publuc 公有。如果不写默认是公有。

  1. class Person {
  2. public str: string;
  3. str1:string
  4. constructor() {
  5. this.str = '公有属性';
  6. this.str1 = '公有'
  7. }
  8. // 公有方法
  9. public pubFun() {
  10. console.log(this.str);
  11. }
  12. pubFun1() {
  13. console.log(this.str1);
  14. }
  15. }

private

private 私有的,只能在自己内部使用,外部不能访问。子类中也无法使用

  1. class Person {
  2. // 私有的变量
  3. private pri :string;
  4. constructor() {
  5. this.priFun(); // 私有的 只能自己使用
  6. }
  7. // 私有的方法
  8. private priFun(){
  9. console.log(this.pri);
  10. }
  11. }
  12. const p = new Person();
  13. // p.priFun(); // error

protected
protected 私有的。只能自己使用或者在子类中使用

  1. class Person {
  2. private pri:string;
  3. // 私有 但是在继承中可以使用
  4. protected pro :string;
  5. constructor() {
  6. this.pri = '私有,只能在自己类中使用';
  7. this.pro = '私有属性,在继承中可以使用';
  8. }
  9. private priFun(){
  10. console.log(this.pri);
  11. }
  12. protected proFun(){
  13. console.log(this.pro);
  14. }
  15. }
  16. class Xiao extends Person{
  17. get(){
  18. super.proFun()
  19. }
  20. NotGet(){
  21. super.priFun(); /// 属性“priFun”为私有属性,只能在类“Person”中访问。ts(2341)
  22. }
  23. }
  24. const p = new Person();
  25. p.proFun(); // 属性“proFun”受保护,只能在类“Person”及其子类中访问。ts(2445)
  26. p.priFun(); // 属性“priFun”为私有属性,只能在类“Person”中访问。ts(2341)
  27. const x = new Xiao();
  28. x.get();

readonly

readonly 只读不能修改

  1. class Person {
  2. readonly read :string = '123';
  3. setRead(){
  4. this.read = '321' // 无法分配到 "read" ,因为它是只读属性。ts(2540)
  5. }
  6. }