一、TypeScript中的静态属性、静态方法

  • es5中的静态属性、方法
    1. function Person() {
    2. this.run1 = function () { } // 实例方法
    3. }
    4. Person.name = '哈哈哈'; // 静态属性
    5. Person.run2 = function () { } // 静态方法
    6. var p = new Person();
    7. Person.run2(); // 静态方法的调用

1、ts中的静态属性、方法
  1. class Person {
  2. public name: string;
  3. public age: number = 20;
  4. static sex = "男"; // 静态属性
  5. constructor(name: string) {
  6. this.name = name;
  7. }
  8. run() {
  9. alert(`${this.name}在运动`)
  10. }
  11. work() {
  12. alert(`${this.name}在工作`)
  13. }
  14. static print() {
  15. // 静态方法里面没法直接调用类里面的属性,想要调用类里面的属性需要把属性变为静态属性
  16. alert('print方法' + Person.sex);
  17. }
  18. }
  19. Person.print(); // 调用静态方法
  20. console.log(Person.sex); // 调用静态属性

二、多

  • 父类定义一个方法不去实现,让继承它的子类去实现 每一个子类有不同的表现
  • 多态属于继承
    1. class Animal {
    2. name: string;
    3. constructor(name: string) {
    4. this.name = name;
    5. }
    6. eat() { // 具体吃什么不知道,继承它的子类去实现每一个子类的表现不一样
    7. console.log('吃的方法')
    8. }
    9. }
    10. class Dog extends Animal {
    11. constructor(name: string) {
    12. super(name)
    13. }
    14. eat() {
    15. return this.name + '吃粮食'
    16. }
    17. }
    18. class Cat extends Animal {
    19. constructor(name: string) {
    20. super(name)
    21. }
    22. eat() {
    23. return this.name + '吃老鼠'
    24. }
    25. }

三、抽象类

  • 它是提供其他类继承的基类,不能直接被实例化
  • 用abstract关键字定义抽象类和抽象方法,抽象类中的抽象方法不包含具体实现并且必须在派生类中实现
  • abstract抽象方法只能放在抽象类里面
  • 抽象类和抽象方法用来定义标准,标准:Animal 这个类要求它的子类必须包含eat方法 ```typescript // 标准:Animal 这个类要求它的子类必须包含eat方法 abstract class Animal { public name: string; constructor(name: string) {

      this.name = name;
    

    } abstract eat(): any; // 抽象方法不包含具体实现并且必须在派生类中实现 run() {

      console.log('其他方法可以不实现')
    

    } } // var a = new Animal() // 错误的写法,无法直接实例化

class Dog extends Animal { //抽象类的子类必须实现抽象类里面的抽象方法 constructor(name: any) { super(name) } eat() { console.log(this.name + ‘吃粮食’) } } var d = new Dog(‘小花花’); // 现在可以实例化了 d.eat(); ```