类与继承

TypeScript作为JavaScript的超集,为JavaScript带来了完整的面向对象编程(OOP)能力。本文将深入探讨TypeScript中的类与继承机制,这是面向对象编程中最核心的概念之一。

类的基本概念

在TypeScript中,类是一种创建对象的蓝图,它定义了对象的属性和方法:

typescript 复制代码
class Person {
    // 属性
    name: string;
    age: number;
    
    // 构造函数
    constructor(name: string, age: number) {
        this.name = name;
        this.age = age;
    }
    
    // 方法
    greet() {
        console.log(`Hello, my name is ${this.name} and I'm ${this.age} years old.`);
    }
}

// 创建实例
const john = new Person("John", 30);
john.greet(); // 输出: Hello, my name is John and I'm 30 years old.

访问修饰符

TypeScript提供了三种访问修饰符来控制类成员的可见性:

  1. public:默认修饰符,成员可以在任何地方访问
  2. private:成员只能在类内部访问
  3. protected:成员可以在类内部和子类中访问
typescript 复制代码
class Employee {
    public name: string;
    private salary: number;
    protected department: string;
    
    constructor(name: string, salary: number, department: string) {
        this.name = name;
        this.salary = salary;
        this.department = department;
    }
    
    public getSalary(): number {
        return this.salary; // 可以在类内部访问private成员
    }
}

继承机制

继承是OOP的核心概念之一,它允许一个类(子类)继承另一个类(父类)的属性和方法:

typescript 复制代码
class Animal {
    name: string;
    
    constructor(name: string) {
        this.name = name;
    }
    
    move(distance: number = 0) {
        console.log(`${this.name} moved ${distance}m.`);
    }
}

class Dog extends Animal {
    breed: string;
    
    constructor(name: string, breed: string) {
        super(name); // 调用父类构造函数
        this.breed = breed;
    }
    
    bark() {
        console.log("Woof! Woof!");
    }
    
    // 重写父类方法
    move(distance: number = 5) {
        console.log(`${this.name} the ${this.breed} is running...`);
        super.move(distance); // 调用父类方法
    }
}

const dog = new Dog("Buddy", "Golden Retriever");
dog.bark(); // 输出: Woof! Woof!
dog.move(); // 输出: Buddy the Golden Retriever is running...
            //       Buddy moved 5m.

抽象类

抽象类是不能被实例化的类,通常用作其他类的基类:

typescript 复制代码
abstract class Shape {
    abstract getArea(): number; // 抽象方法,必须在子类中实现
    
    printArea() {
        console.log(`Area: ${this.getArea()}`);
    }
}

class Circle extends Shape {
    radius: number;
    
    constructor(radius: number) {
        super();
        this.radius = radius;
    }
    
    getArea(): number {
        return Math.PI * this.radius ** 2;
    }
}

const circle = new Circle(5);
circle.printArea(); // 输出: Area: 78.53981633974483

接口与类

TypeScript中的接口可以用来定义类的结构:

typescript 复制代码
interface ClockInterface {
    currentTime: Date;
    setTime(d: Date): void;
}

class Clock implements ClockInterface {
    currentTime: Date = new Date();
    
    setTime(d: Date) {
        this.currentTime = d;
    }
    
    constructor(h: number, m: number) {
        this.currentTime.setHours(h, m);
    }
}

静态成员

静态成员属于类本身,而不是类的实例:

typescript 复制代码
class MathHelper {
    static PI: number = 3.14159;
    
    static calculateCircleArea(radius: number): number {
        return this.PI * radius * radius;
    }
}

console.log(MathHelper.PI); // 3.14159
console.log(MathHelper.calculateCircleArea(5)); // 78.53975

总结

TypeScript的类与继承机制为JavaScript开发者提供了强大的面向对象编程能力。通过类、继承、抽象类、接口等特性,开发者可以构建更加结构化和可维护的代码。理解这些概念对于构建大型应用程序至关重要,它们有助于代码的组织、复用和扩展。