Ts的类

1.修饰符

public 公有 父类(自身)以及子类和外部都能访问
protected 受保护 父类(自身)以及子类都能访问 但是外部不能访问
private  私有的 父类(自身)可以访问 但是子类和外部不能访问

2.基本使用

class Person {
  //   name: string;

  static age: number = 18; // 静态属性

  //   constructor(name: string) {
  //     this.name = name;
  //   }

  // 上面两个的合并 是一种缩写
  constructor(protected name: string) {
    this.name = name;
  }

  run(): void {
    console.log(this.name + "正在运动");
    console.log(Person.age); //这里是可以用静态变量的
  }

  // 类里面的方法,有返回值  [propName:string]: any表示不定参数
  getInfo(): { id: string, name: string, [propName:string]: any } {
    return {
      age1: 18,
      age: 18,
      id: "1",
      name: this.name,
    };
  }

  // 类里面的方法,无返回值
  printName(profix: string): void {
    console.log(profix + ":" + this.name);
  }

  // getter
  get myName() {
    return this.name;
  }

  // setter
  set myName(newVal) {
    this.name = newVal;
  }

  // 静态方法
  static getStaticInfo(): void {
    Person.age = 20;
    // 静态方法里不能用非静态变量 如 上面的name,只能用静态变量
    console.log(Person.age);
  }
}

let p = new Person("战三");
p.run(); // 战三正在运动 18
console.log(p.getInfo()); // {name:"战三"}
Person.getStaticInfo(); //20

// console.log(p.name) // 因为是protected,所以外部不能访问 这里会报错

3.继承

// 继承
class Child extends Person {
  public count: number;
  constructor(name: string, count: number) {
    super(name); //子类继承 要实现super
    this.count = count;
  }
  // 多态 重写父级方法
  printName(profixChild: string): void {
    console.log(profixChild + ":" + this.name + "child"); // 因为是protected,所以子集能访问,如果是private,就会报错
  }
}
let c = new Child("子集", 20);

4.抽象类(可以规定类的一些标准)

// 抽象类 (可以规定类的一些标准)
abstract class People1 {
  age: number;
  constructor(age: number) {
    this.age = age;
  }
  printAge() {
    console.log(this.age);
  }
  abstract name: string; // 抽象属性 必须子类实现
  abstract getName(): string; // 抽象方法,必须子类实现
}

class Man extends People1 {
  public name: string; // 实现抽象属性
  constructor(age: number, name: string) {
    super(age);
    this.name = name;
  }
  // 实现抽象方法
  getName(): string {
    return this.name + "Child";
  }
}

let mm = new Man(18, "张三");
mm.printAge();
console.log(mm.getName());

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值