TypeScript 自学笔记4 类

前言

  • 自学TypeScript第四天
  • 今天对学过java的很友好基本上都是后端的东西

介绍

  • 传统的JavaScript程序使用函数和基于原型的继承来创建可重用的组件,但对于熟悉使用面向对象方式的程序员来讲就有些棘手,因为他们用的是基于类的继承并且对象是由类构建出来的。 从ECMAScript 2015,也就是ECMAScript 6开始,JavaScript程序员将能够使用基于类的面向对象的方式。 使用TypeScript,我们允许开发者现在就使用这些特性,并且编译后的JavaScript可以在所有主流浏览器和平台上运行,而不需要等到下个JavaScript版本。

  • 类我们学过后端的话对这个就会非常的熟悉,类在后端是一个非常常用的属性,在es6开始js增加了类
  • 这个添加对很多开发者来说算是一个福音
  • 如果你使用过C#或Java,你会对这种语法非常熟悉。 我们声明一个 Greeter类。这个类有3个成员:一个叫做 greeting的属性,一个构造函数和一个 greet方法。

  • 你会注意到,我们在引用任何一个类成员的时候都用了 this。 它表示我们访问的是类的成员。

  • 最后一行,我们使用 new构造了 Greeter类的一个实例。 它会调用之前定义的构造函数,创建一个 Greeter类型的新对象,并执行构造函数初始化它。

  • 作为一个学过后端的人,我对这一个类感到非常熟悉也很容易上手
1
2
3
4
5
6
7
8
9
10
11
12
13
class Greeter {
greeting: string;
constructor(message: string) {
this.greeting = message;
}
greet() {
return "Hello, " + this.greeting;
}
}

let greeter = new Greeter("world");

console.log(greeter.greet())

继承

  • 继承也是很常见的
  • 在TypeScript里,我们可以使用常用的面向对象模式。 基于类的程序设计中一种最基本的模式是允许使用继承来扩展现有的类。
  • 很简单的说就是,儿子继承了爸爸的所有东西

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    class Animal {
    move(distanceInMeters: number = 0) {
    console.log(`Animal moved ${distanceInMeters}m.`);
    }
    }

    class Dog extends Animal {
    bark() {
    console.log('Woof! Woof!');
    }
    }

    const dog = new Dog();
    dog.bark();
    dog.move(10);
    dog.bark();
  • 这个例子展示了最基本的继承:类从基类中继承了属性和方法。 这里, Dog是一个 派生类,它派生自 Animal 基类,通过 extends关键字。 派生类通常被称作 子类,基类通常被称作 超类。


  • 这个例子展示了一些上面没有提到的特性。 这一次,我们使用 extends关键字创建了 Animal的两个子类: Horse和 Snake。
  • 与前一个例子的不同点是,派生类包含了一个构造函数,它 必须调用 super(),它会执行基类的构造函数。 而且,在构造函数里访问 this的属性之前,我们 一定要调用 super()。 这个是TypeScript强制执行的一条重要规则。
  • 这个例子演示了如何在子类里可以重写父类的方法。 Snake类和 Horse类都创建了 move方法,它们重写了从 Animal继承来的 move方法,使得 move方法根据不同的类而具有不同的功能。 注意,即使 tom被声明为 Animal类型,但因为它的值是 Horse,调用 tom.move(34)时,它会调用 Horse里重写的方法:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    class Animal {
    // 属性
    name: string;
    // 构造函数
    constructor(theName: string) { this.name = theName; }
    // 内部方法
    move(distanceInMeters: number = 0) {
    console.log(`${this.name} moved ${distanceInMeters}m.`);
    }
    }

    class Snake extends Animal {
    // 构造函数,super调用父级构造函数
    constructor(name: string) { super(name); }
    // 子类重写方法
    move(distanceInMeters = 5) {
    console.log("Slithering...");
    // 内部调用了父级的方法
    super.move(distanceInMeters);
    }
    }

    class Horse extends Animal {
    constructor(name: string) { super(name); }
    move(distanceInMeters = 45) {
    console.log("Galloping...");
    super.move(distanceInMeters);
    }
    }

    let sam = new Snake("Sammy the Python");
    let tom: Animal = new Horse("Tommy the Palomino");

    sam.move();
    tom.move(34);

公共,私有与受保护的修饰符

默认 public 公共类型

  • 我以前学习java的时候这个属性的要写出来的
  • 但是js给我们默认了
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    class Animal {
    public name: string;
    public constructor(theName: string) { this.name = theName; }
    public move(distanceInMeters: number) {
    console.log(`${this.name} moved ${distanceInMeters}m.`);
    }
    }

    // 我们平时都是这么写的
    class Animal {
    name: string;
    constructor(theName: string) { this.name = theName; }
    move(distanceInMeters: number) {
    console.log(`${this.name} moved ${distanceInMeters}m.`);
    }
    }

理解 private 私有化

  • private 就是私有化,简单点说就是唯独我有,你们虽都不可以用只可以我自己用
  • 我自己拥有的连儿子都不可用唯独我自己可以用
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Animal {
private name: string;
constructor(theName: string) { this.name = theName; }
}

// 定义使用报错
new Animal("Cat").name; // 错误: 'name' 是私有的.

// 我们来试试在继承中能不能用,儿子继承父亲的东西

class Test {
constructor(test: string) {
super(test)
}

Test () {
console.log(this.name) // 注意了,这样也是错误的
}
}

  • 其实就是说不是同一个爸爸生出来的都不算有关系。
  • TypeScript使用的是结构性类型系统。 当我们比较两种不同的类型时,并不在乎它们从何处而来,如果所有成员的类型都是兼容的,我们就认为它们的类型是兼容的
  • 然而,当我们比较带有 private或 protected成员的类型的时候,情况就不同了。 如果其中一个类型里包含一个 private成员,那么只有当另外一个类型中也存在这样一个 private成员, 并且它们都是来自同一处声明时,我们才认为这两个类型是兼容的。 对于 protected成员也使用这个规则
  • 这个例子中有 Animal和 Rhino两个类, Rhino是 Animal类的子类。 还有一个 Employee类,其类型看上去与 Animal是相同的。 我们创建了几个这些类的实例,并相互赋值来看看会发生什么。 因为 Animal和 Rhino共享了来自 Animal里的私有成员定义 private name: string,因此它们是兼容的。 然而 Employee却不是这样。当把 Employee赋值给 Animal的时候,得到一个错误,说它们的类型不兼容。 尽管 Employee里也有一个私有成员 name,但它明显不是 Animal里面定义的那个。
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    class Animal {
    private name: string;
    constructor(theName: string) { this.name = theName; }
    }

    class Rhino extends Animal {
    constructor() { super("Rhino"); }
    }

    class Employee {
    private name: string;
    constructor(theName: string) { this.name = theName; }
    }

    let animal = new Animal("Goat");
    let rhino = new Rhino();
    let employee = new Employee("Bob");

    animal = rhino;
    animal = employee

理解 protected (比私有低一个级别)

  • 和私有化几乎一模一样
  • 这个属性比私有化低一个级别,儿子可以用了
  • 在继承中还是可以使用的
  1. 属性
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    // 这个例子比较经典
    class Person {
    protected name: string;
    constructor(name: string) { this.name = name; }
    }

    // 继承
    class Employee extends Person {
    private department: string;

    constructor(name: string, department: string) {
    super(name)
    this.department = department;
    }

    public getElevatorPitch() {
    // 继承类里面是可以使用父级的name的
    return `Hello, my name is ${this.name} and I work in ${this.department}.`;
    }
    }

    let howard = new Employee("Howard", "Sales");
    console.log(howard.getElevatorPitch());
    // 外面就不可用了
    console.log(howard.name); // 错误

  1. 构造函数也是可以被保护起来的
  • 在外面是无法使用的哈哈哈,起到了很好的保护作用
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    class Person {
    protected name: string;
    protected constructor(theName: string) { this.name = theName; }
    }

    // Employee 能够继承 Person
    class Employee extends Person {
    private department: string;

    constructor(name: string, department: string) {
    super(name);
    this.department = department;
    }

    public getElevatorPitch() {
    return `Hello, my name is ${this.name} and I work in ${this.department}.`;
    }
    }

    let howard = new Employee("Howard", "Sales");
    let john = new Person("John"); // 错误: 'Person' 的构造函数是被保护的.

readonly修饰符 (只读)

  • 你可以使用 readonly关键字将属性设置为只读的。 只读属性必须在声明时或构造函数里被初始化
  • 说白了只能看看不能改变,一开始就定义好
  • 就好像你妈打你只能挨着不能还手
    1
    2
    3
    4
    5
    6
    7
    8
    9
    class Octopus {
    readonly name: string;
    readonly numberOfLegs: number = 8;
    constructor (theName: string) {
    this.name = theName;
    }
    }
    let dad = new Octopus("Man with the 8 strong legs");
    dad.name = "Man with the 3-piece suit"; // 错误! name 是只读的.

参数属性

  • 参数的自带属性然我们可以减少一些写法
  • 在上面的例子中,我们必须在Octopus类里定义一个只读成员 name和一个参数为 theName的构造函数,并且立刻将 theName的值赋给 name,这种情况经常会遇到。 参数属性可以方便地让我们在一个地方定义并初始化一个成员。 下面的例子是对之前 Octopus类的修改版,使用了参数属性:
  • 参数属性通过给构造函数参数前面添加一个访问限定符来声明。 使用 private限定一个参数属性会声明并初始化一个私有成员;对于 public和 protected来说也是一样。
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    // 在这里可以验证,自读属性会自动初始化一个私有成员
    class Octopus {
    readonly numberOfLegs: number = 8;
    constructor(readonly name: string) {
    // 在这里可以得到证实
    this.name = name;
    }
    test () {
    return this.name;
    }
    }

    let test1 = new Octopus('YHF');
    console.log(test1.test()); // YHF

存取器 (get/set,es5以上才可以用,编译会报错但是可以使用的)

  • 这个get/set 写java的真的在熟悉不过了,这个是结合私有化属性使用的
  • 私有化属性,就是通过get/set来限制学习
  • TypeScript支持通过getters/setters来截取对对象成员的访问。 它能帮助你有效的控制对对象成员的访问
  • 注意:首先,存取器要求你将编译器设置为输出ECMAScript 5或更高。 不支持降级到ECMAScript 3。 其次,只带有 get不带有 set的存取器自动被推断为 readonly。 这在从代码生成 .d.ts文件时是有帮助的,因为利用这个属性的用户会看到不允许够改变它的值。
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    // 版本1
    // 在这里面fullname可以随意更改,确实方便也带来了很多麻烦
    class Employee {
    fullName: string;
    }

    let employee = new Employee();
    employee.fullName = "Bob Smith";
    if (employee.fullName) {
    console.log(employee.fullName);
    }

    // 升级版,设置权限
    let passcode = "secret passcode";

    class Employee {
    private _fullName: string;

    get fullName(): string {
    return this._fullName;
    }

    set fullName(newName: string) {
    if (passcode && passcode == "secret passcode") {
    this._fullName = newName;
    }
    else {
    console.log("Error: Unauthorized update of employee!");
    }
    }
    }

    let employee = new Employee();
    employee.fullName = "Bob Smith";
    if (employee.fullName) {
    alert(employee.fullName);
    }

静态属性

  • 类的静态属性,每一次调用都是直接通过类名去调用
  • 哪里都可用的很广泛,无需实例,调用就是实例
  • 我们也可以创建类的静态成员,这些属性存在于类本身上面而不是类的实例上。 在这个例子里,我们使用 static定义 origin,因为它是所有网格都会用到的属性。 每个实例想要访问这个属性的时候,都要在 origin前面加上类名。 如同在实例属性上使用 this.前缀来访问属性一样,这里我们使用 Grid.来访问静态属性。
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    class Grid {
    static origin = {x: 0, y: 0};
    calculateDistanceFromOrigin(point: {x: number; y: number;}) {
    let xDist = (point.x - Grid.origin.x);
    let yDist = (point.y - Grid.origin.y);
    return Math.sqrt(xDist * xDist + yDist * yDist) / this.scale;
    }
    constructor (public scale: number) { }
    }

    let grid1 = new Grid(1.0); // 1x scale
    let grid2 = new Grid(5.0); // 5x scale

    // 这个今天属性在外面页面可以用的
    console.log(Grid.origin)

    console.log(grid1.calculateDistanceFromOrigin({x: 10, y: 10}));
    console.log(grid2.calculateDistanceFromOrigin({x: 10, y: 10}));

抽象类 (和继承差不多)

  • 又是一个后端的最爱
  • 抽象类,就是只是写元素名,方法名,但继承了这个抽象类,并实例化里面但抽象方法
  • 抽象类做为其它派生类的基类使用。 它们一般不会直接被实例化。 不同于接口,抽象类可以包含成员的实现细节。 abstract关键字是用于定义抽象类和在抽象类内部定义抽象方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
// 抽象类
abstract class Department {

constructor(public name: string) {
}

printName(): void {
console.log('Department name: ' + this.name);
}

// 抽象方法
abstract printMeeting(): void; // 必须在派生类中实现
}

// 继承抽象类
class AccountingDepartment extends Department {

constructor() {
super('Accounting and Auditing'); // 在派生类的构造函数中必须调用 super()
}

printMeeting(): void {
console.log('The Accounting Department meets each Monday at 10am.');
}

generateReports(): void {
console.log('Generating accounting reports...');
}
}

// 声明一个抽象类但属性
let department: Department; // 允许创建一个对抽象类型的引用
// 抽象类是不可实例的
department = new Department(); // 错误: 不能创建一个抽象类的实例
department = new AccountingDepartment(); // 允许对一个抽象子类进行实例化和赋值
department.printName();
department.printMeeting();
// 这个错误并不是因为不可以这样去写,只是声明但时候抽象类里面没有
department.generateReports(); // 错误: 方法在声明的抽象类中不存在

高级技巧

构造函数

  • 当你在TypeScript里声明了一个类的时候,实际上同时声明了很多东西。 首先就是类的 实例的类型
  • 这里,我们写了 let greeter: Greeter,意思是 Greeter类的实例的类型是 Greeter。 这对于用过其它面向对象语言的程序员来讲已经是老习惯了。
  • let Greeter将被赋值为构造函数。 当我们调用 new并执行了这个函数后,便会得到一个类的实例。 这个构造函数也包含了类的所有静态属性。 换个角度说,我们可以认为类具有 实例部分与 静态部分这两个部分。
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    class Greeter {
    greeting: string;
    constructor(message: string) {
    this.greeting = message;
    }
    greet() {
    return "Hello, " + this.greeting;
    }
    }

    let greeter: Greeter;
    greeter = new Greeter("world");
    console.log(greeter.greet());

  • 这里会比较绕不过是解释构造函数
  • 这个例子里, greeter1与之前看到的一样。 我们实例化 Greeter类,并使用这个对象。 与我们之前看到的一样。
    再之后,我们直接使用类。 我们创建了一个叫做 greeterMaker的变量。 这个变量保存了这个类或者说保存了类构造函数。 然后我们使用 typeof Greeter,意思是取Greeter类的类型,而不是实例的类型。 或者更确切的说,”告诉我 Greeter标识符的类型”,也就是构造函数的类型。 这个类型包含了类的所有静态成员和构造函数。 之后,就和前面一样,我们在 greeterMaker上使用 new,创建 Greeter的实例。
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    class Greeter {
    static standardGreeting = "Hello, there";
    greeting: string;
    greet() {
    if (this.greeting) {
    return "Hello, " + this.greeting;
    }
    else {
    return Greeter.standardGreeting;
    }
    }
    }

    let greeter1: Greeter;
    greeter1 = new Greeter();
    console.log(greeter1.greet());

    let greeterMaker: typeof Greeter = Greeter;
    greeterMaker.standardGreeting = "Hey there!";

    let greeter2: Greeter = new greeterMaker();
    console.log(greeter2.greet());

把类当做接口使用

  • 如上一节里所讲的,类定义会创建两个东西:类的实例类型和一个构造函数。 因为类可以创建出类型,所以你能够在允许使用接口的地方使用类。
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    class Point {
    x: number;
    y: number;
    }

    interface Point3d extends Point {
    z: number;
    }

    let point3d: Point3d = {x: 1, y: 2, z: 3};

后记

  • 这个就是我学习Ts的第四天的笔记,欢迎更多的同行大哥指导交流
  • 欢迎进入我的博客https://yhf7.github.io/
  • 如果有什么侵权的话,请及时添加小编微信以及qq也可以来告诉小编(905477376微信qq通用),谢谢!
-------------本文结束感谢您的阅读-------------
0%