类的封装

eat方法可以直接调用去实现一个功能, 但是你不需要知道eat里面具体怎么去实现

  1. class Animal {
  2. name: string;
  3. constructor(name: string) {
  4. this.name = name;
  5. }
  6. eat(food: string) {
  7. console.log(this.name, "is eating ", food);
  8. }
  9. }

类的继承

Dog类继承自Animal类, 所以dog实例会拥有Animal类的所有属性和方法

  1. class Dog extends Animal {
  2. constructor(name: string) {
  3. // 派生类的构造函数必须包含 "super" 调用。
  4. super(name);
  5. }
  6. }

类的多态

Dog类和Cat都继承自Animal类, 所以都有eat方法, 但是Cat对eat方法进行了重载, 所以在调用eat方法时, 会有不同的表现, 这就叫类的多态

  1. class Cat extends Animal {
  2. eat() {
  3. console.log("I don't wanna eat!");
  4. }
  5. }
  6. const dog = new Dog("dog");
  7. const cat = new Cat("dog");
  8. dog.eat("bread");
  9. cat.eat();

静态属性

  1. class Bear extends Animal {
  2. static shape: string = "round";
  3. static bite() {
  4. console.log("I will bite you!");
  5. }
  6. }
  7. console.log(Bear.shape);
  8. Bear.bite();

typescript的修饰符

public外部可读(这个是默认的)

private仅限内部可读(调用)

protected

private和protected的异同
相同点: private和protected修饰的方法或属性都无法通过外部访问或调用
不同点: private修饰的属性或方法不可以在子类中通过super.属性名或者super.方法名拿到, 但是protected修饰的方法或属性可以

  1. class People {
  2. private name: string;
  3. protected age: number = 17;
  4. constructor(name: string, age: number) {
  5. this.name = name;
  6. }
  7. eat(food: string) {
  8. console.log(`${this.name} is ear ${food}`);
  9. }
  10. }
  11. class Women extends People {
  12. run() {
  13. console.log(this.age);
  14. this.eat("orange");
  15. }
  16. }
  17. class TallWomen extends Women {
  18. fight() {
  19. console.log(this.age);
  20. }
  21. }
  22. const xiaoMing = new People("Mr.Ming", 18);
  23. // xiaoMing.eat("rice");
  24. // console.log(xiaoMing.name);
  25. // console.log(xiaoMing.age);
  26. const xiaoMei = new Women("Mrs.Mei", 20);
  27. xiaoMei.run();
  28. const mary = new TallWomen("Mary", 27);
  29. mary.fight();

readonly只读