Day25 :【TypeScript 学起来】Class 的继承、修饰符、abstract、static

今天继续笔记class,剩最後5天了!
若有错误,欢迎留言指教,感恩的心。


extends 继承

这个跟JavaScript相同, 使用 extends 继承类别, 建立子类别,子类别可以使用父层的东西。如下例子,依不同参数型别来使用父层的method greet。

class Base {
  greet() {
    console.log("Hello, world!");
  }
}
 
class Derived extends Base {
  greet(name?: string) {
    if (name === undefined) {
      super.greet();
    } else {
      console.log(`Hello, ${name.toUpperCase()}`);
    }
  }
}
 
const a = new Derived();
a.greet(); //Hello, world!
a.greet("reader"); //Hello, READER

Public & Private & Protected

TypeScript 可以使用三种访问修饰符(Access Modifiers),分别是 public、private 和 protected。

  • 都没写的话,预设值为 public
  • public 修饰的属性或方法是公有的,可以在任何地方被访问到,预设所有的属性和方法都是 public 的
  • private 修饰的属性或方法是私有的,不能在宣告它的类别的外部访问
  • protected 修饰的属性或方法是受保护的,它和 private 类似,区别是它在子类别中也是允许被访问的
class Person {
  public name: string; //公有
  protected age: number; //受保护的
  private phone: number; //私有

  constructor(name: string, age: number, phone: number) {
    this.name = name;
    this.age = age;
    this.phone = phone;
  }
  getName(): string {
    return this.name;
  }
  setName(name: string): void {
    this.name = name;
  }
}
class Child extends Person {
  constructor(name: string, age: number, phone: number) {
    super(name, age, phone);
  }
  desc() {
    console.log(`${this.name}${this.age}${this.phone}`);
    // phone 为私有属性, 只能在 Person class 里面使用
  }
}
let child = new Child("iris", 18, 0912345678);
console.log(child.name);
console.log(child.age); //只能在Person及子类别里面使用 error: Property 'age' is protected and only accessible within class 'Person' and its subclasses.
console.log(child.phone); //只能在class Person里使用 error: Property 'phone' is private and only accessible within class 'Person'.


private constructor

该类别不允许被继承或者实例化:

class Person2 {
    public name:string;
    private constructor (name:string) {
        this.name = name;
  }
}
class Child2 extends Person2 {  //无法被继承 error: Cannot extend a class 'Person2'. Class constructor is marked as private.
    constructor (name) {
        super(name);
    }
}

let a2 = new Child2('iris');

protected constructor

允许在子类别中使用:

class Person3 {
    public name:string;
    protected constructor (name:string) {
        this.name = name;
  }
}
class Child3 extends Person3 {  
    constructor (name:string) {
        super(name);
        console.log(name);
    }
}

let a3 = new Child3('iris');
console.log(a3); //Child3 { name: 'iris' }

Abstract 抽象

abstract 用於定义抽象类别和其中的抽象方法。

抽象类别是不允许被实例化的,下面例子我们定义了抽象类别 Animal,并且定义了一个抽象方法 sayHi。在实例化抽象类别的时候报错了。:

abstract class Animal {
  public name;
  public constructor(name:string) {
      this.name = name;
  }
  public abstract sayHi(): void;
}

let b = new Animal('Tom'); //error: Cannot create an instance of an abstract class.

抽象类别中的抽象方法必须被子类别实现:

abstract class Animal2 {
  public name;
  public constructor(name:string) {
      this.name = name;
  }
  public abstract sayHi():void;
}

class Cat extends Animal {
  public sayHi() {
      console.log(`Meow, My name is ${this.name}`);
  }
}

let cat = new Cat('Tom');

static

使用 static 修饰符修饰的方法称为静态方法,它们不需要实例化,而是直接透过类别来呼叫:

class Animal3 {
    public name;
    public constructor(name:string) {
        this.name = name;
    }
    static isAnimal(c:object) {
        return c instanceof Animal;
    }
}

let c = new Animal3('Tom');
let d = Animal3.isAnimal(c); 
console.log(d); //true
c.isAnimal(c); //c.isAnimal is not a function

可以搭配 public 、 protected 和 private 一起使用

class MyClass {
  private static x = 0;
}
console.log(MyClass.x); //error:Property 'x' is private and only accessible within class 'MyClass'.

static 也能够继承

class Base2 {
  static getGreeting() {
    return "Hello world";
  }
}
class Derived2 extends Base2 {
  myGreeting = Derived2.getGreeting();
}

let derived2 = new Derived2();
console.log(derived2);

今天是个有意义的日子,天气好好
感谢阅读,明天见~


参考资料

https://willh.gitbook.io/typescript-tutorial/advanced/class
https://www.typescriptlang.org/docs/handbook/2/classes.html


<<:  Day-25 PyTorch 的 CNN Model

>>:  DAY25 - 展现成果,建立成果页面

Day10 Scanner(Ⅱ)

Scanner 常使用到的Methods 整数 nextInt() 2.小数 nextDouble(...

Day 5 - Using Argon2 for Password Verifying with ASP.NET Web Forms C# 使用 Argon2 验证密码

=x= 🌵 Sign In page 後台登入密码验证。 验证流程介绍 : 📌 使用者於登入页面输入...

Day5 Let's ODOO: Model(2) Fields

延续前日介绍,今天我们来讲Model内的fields延续昨日范例 # -*- coding: utf...

Day 29 - 使用 Config 为 NestJS 专案拆分不同开发环境

前言 终於来到了第 29 天了,也就是名义上技术篇章的最後一篇了 XDD,到了今天我还真是突然不知道...

Day4 如何安装Git的环境

大家好我是乌木白,今日要和大家分享如何安装Git的环境! 如何安装Git的环境 安装在 Windo...