Typescript 类

前言

原型prototype是javascript的一大特性,基于原型可以实现javascript中的继承。自从es6引入了class,我们可以在javascript使用类。但es6中的class只是prototype的语法糖。在typescript中我们基本可以向传统编程语言一样使用class来帮助我们实现面向对象编程。

  • 与#c相比,ts声明类的程序成员是默认为public,也可以显示声明public
  • 与es6相比,es6 class没有public,private等修饰符

es6 class和ts class子类如果声明了构造函数,必须调用super,在使用this前也需要调用super,如果子类没有显示声明constructor构造函数,那么会默认添加。

继承

继承是类的一大特性,可以通过extends实现继承,在ts中,父类又被称作基类,子类又被称作为派生类。

属性方法继承

类的继承最基本的特点是派生类继承继承基类的属性和方法

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();

改写父类方法

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 {
    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);

派生类Horse和Snake都重新实现了基类的move方法,并通过super关键字调用父类的move方法。

派生类中声明了constructor函数,必须显示调用super

super可以在派生类其他方法中使用,不仅仅是在construtor,super可以理解为一个引用,指向基类。

单继承

class P {}

class C extends P {}

多继承

class P1 {}
class P2 {}
class C extends p1, p2 {
  
}

public

类的成员默认为public,可以明确将一个类的成员标记为public

class P {
  public constructor(name: string) {
  	this.name = name
  }
  
  public name: string
}

private

当类的成员被标记为private时,不能在类的外部访问

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

new Animal("Cat").name; // 错误: 'name' 是私有的.

Typescript中比较两种不同类型时,只要成员类型兼容,就认为它们的类型是相同的。

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

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

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

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

animal = rhino;      // ok
animal = employee;   // ok

当比较含有private或者protected成员的类型时,如果其中一个类型里包含一个private或者protected成员,那么只有当另外一个类型中也存在这样一个private成员,并且它们都是来自同一处声明时,ts才认为这两个类型是兼容的。

class Animal {
    protected name: string;
    constructor(theName: string) { this.name = theName; }
}

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

class Employee {
    protected 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; // 错误不能将类型“Employee”分配给类型“Animal”。
  					//属性“name”受保护,但类型“Employee”并不是从“Animal”派生的类

protected

protected和private的行为类似,唯一不同的是,private属性在派生类中不能访问,但protected属性在派生类中可以访问。

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() {
        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); // 错误:属性“name”受保护,只能在类“Person”及其子类中访问

构造函数也可以被标记为protected,这意味着不能在类的外部实例化,也就是通过new调用,但可以被继承

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}.`;
    }

    getName() {
        console.log(this.name)
    }
}

let howard = new Employee("Howard", "Sales");
howard.getName()   // Howard
let john = new Person("John"); // 错,类“Person”的构造函数是受保护的,仅可在类声明中访问

抽象类

abstract声明抽象类和抽象类的成员(属性或者方法)。

抽象类中的抽象方法不包含具体实现并且必须在派生类中实现。

抽象方法的语法与接口方法相似。 两者都是定义方法签名但不包含方法体。 然而,抽象方法必须包含 abstract关键字并且可以包含访问修饰符。

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(); // 错误: 方法在声明的抽象类中不存在
// 当
let department: AccountingDepartment
department = new AccountingDepartment();
department.generateReports();  // ok

其他

readonly修饰符

当使用readonly关键字将属性设置为只读时,只读属性必须在声明时或者构造函数里初始化,当然也可以不初始化,但这个属性值是undefined。

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 是只读的.

参数属性

所谓的参数属性可以理解我一种语法糖,将属性定义和构造函数内部属性初始化合并在constructor构造函数的参数中,改写上面的示例如下:

class Octopus {
    readonly numberOfLegs: number = 8;
    constructor(readonly name: string) {
    }
}

存取器

ts中的存取器就是js中的getter和setter

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";  //setter  
if (employee.fullName) {  //getter
    alert(employee.fullName);
}

使用存取器属性有以下好处

  • 可以在内的外部访问和修改private或protected修饰的属性
  • 可以限制对成员属性的修改

使用存取器属性需要将编译器设置为输出ECMAScript 5或更高,只带有get不带有set的属性会自动被推断为readonly

静态属性

和Es6相同,static修饰符修饰的属性为静态属性,静态属性是类自身的属性而不是实例的属性,不能通过this或者实例来访问静态属性

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(grid1.calculateDistanceFromOrigin({x: 10, y: 10}));
console.log(grid2.calculateDistanceFromOrigin({x: 10, y: 10}));

类和接口

类定义会创建两个东西:类的实例类型和一个构造函数。 因为类可以创建出类型,所以你能够在允许使用接口的地方使用类

class Point {
    x: number;
    y: number;
}

interface Point3d extends Point {
    z: number;
}

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

思维导图

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值