typescript three types of modifiers

Three modifiers and the difference private public protected

class Animals {
    
    
  // 公有属性 public 在class内部或者外部或者子类都可访问,不加修饰符时,默认为 public
  name: string;
  age: number;
  /** 私有属性animalsMotherId,只能在class内部访问,在外部或者子类中都不能访问 */
  private animalsMotherId: number = 1;
  constructor(name: string, age: number) {
    
    
    this.name = name;
    this.age = age;
  }
  getName(): string {
    
    
    return this.name;
  }
  /** 保护属性 只有class内部和子类可以使用,在外部无法使用 */
  protected setName(newName: string): void {
    
    
    this.name = newName;
    console.log(this.name);
  }
  setMotherid(newMotherId: number): void {
    
    
    /** 私有属性 class内部测试  可以正常使用 */ 
    this.animalsMotherId = newMotherId;
  }
}

let dog = new Animals('小汪', 2);

// 私有属性外部测试 在浏览器代码能够正常执行,(因为转为了es5),但编译器会提示报错。
// console.log(dog.animalsMotherId)

// 公有属性外部测试 在class外部可以正常使用
console.log(dog.getName())

// 保护属性外部测试 在浏览器代码能够正常执行,(因为转为了es5),但编译器会提示报错
// dog.setName('小旺');

//子类Cat继承父类Animals
class Cat extends Animals {
    
    
  food: string | undefined;
  constructor(name: string, age: number, food?: string) {
    
    
    super(name, age);
    this.food = food;
  }
  eat() {
    
    
    if (this.food) {
    
    
      console.log(`${
    
    this.name}爱吃${
    
    this.food}`);
    } else {
    
    
      throw new Error('未知食物');
    }
  }
  replaceName(newName: string) {
    
    
    /** 保护属性子类中测试 在子类中正常使用 */
    this.setName(newName);
    /** 公有属性子类中测试 在子类可以正常使用 */
    console.log(this.name);
  }

  getMotherId() {
    
    
    /** 私有属性子类中测试 浏览器转为es5后正常打印 但编译器会报错*/
    console.log(this.animalsMotherId);

    throw new Error('父类私有属性,子类无法访问');
  }
}

let cat1 = new Cat('小喵', 2, '鱼');

console.log(cat1.name, cat1.age);
cat1.replaceName('小花喵');

Guess you like

Origin blog.csdn.net/glorydx/article/details/111171449