TypeScript 类学习笔记

什么是类(Class)?

类是面向对象编程(OOP)中的一个重要概念,它是对一类事物的抽象和封装,可以将数据和行为打包在一起作为一个整体。用类来描述现实世界的物体,可以更好地组织和管理代码。

类的定义

TypeScript 中可以使用 class 关键字来定义一个类,基本语法如下:

typescriptCopy Code
class ClassName { // 成员变量(属性) memberVar: type; // 构造函数 constructor(params: type) { // 初始化成员变量 this.memberVar = params; } // 成员方法 memberMethod() { // 方法体 } }

上述代码中 class 关键字后面跟着类名 ClassName,其中包含了三个部分:成员变量、构造函数和成员方法。成员变量用于存储类的数据,构造函数用于初始化这些数据,成员方法则用于表示类的行为。

类的继承

通过继承,子类可以获得父类的数据和行为,并且还可以添加自己独有的数据和行为。

typescriptCopy Code
class FatherClass { fatherVar: string = "Father"; fatherMethod() { console.log("This is Father's method."); } } class ChildClass extends FatherClass { childVar: string = "Child"; childMethod() { console.log("This is Child's method."); } }

上述代码中,ChildClass 继承了 FatherClass,通过关键字 extends 来表示继承关系。子类可以调用父类的成员变量和成员方法,也可以添加自己的成员变量和成员方法。

类的访问修饰符

访问修饰符用于控制类的成员变量和成员方法的访问权限,分别有 publicprivateprotected

  • public:任何地方都可以访问。
  • private:只有在类的内部才可以访问。
  • protected:类的内部和子类中可以访问。
typescriptCopy Code
class Animal { public name: string; private age: number; protected weight: number; constructor(name: string, age: number, weight: number) { this.name = name; this.age = age; this.weight = weight; } public showInfo() { console.log(`Name: ${this.name}, Age: ${this.age}, Weight: ${this.weight}`); } } class Cat extends Animal { public catchMouse() { console.log(`${this.name} is catching mouse.`); } } const kitty = new Cat("Kitty", 2, 5); console.log(kitty.name); // "Kitty" console.log(kitty.age); // 错误,age 是 private 成员变量 console.log(kitty.weight); // 错误,weight 是 protected 成员变量 kitty.showInfo(); // "Name: Kitty, Age: 2, Weight: 5" kitty.catchMouse(); // "Kitty is catching mouse."

上述代码中,Animal 类包含了三个成员变量和一个成员方法,其中 namepublic 类型,可以在外部访问;ageprivate 类型,只能在类的内部访问;weightprotected 类型,可以在类内部和子类中访问。Cat 继承了 Animal,并添加了自己的方法 catchMouse

实例

typescriptCopy Code
class Person { name: string; age: number; constructor(name: string, age: number) { this.name = name; this.age = age; } public sayHi() { console.log(`Hi, I'm ${this.name}, I'm ${this.age} years old.`); } } const p1 = new Person("Alice", 20); p1.sayHi(); // "Hi, I'm Alice, I'm 20 years old." const p2 = new Person("Bob", 25); p2.sayHi(); // "Hi, I'm Bob, I'm 25 years old."

上述代码中,定义了一个 Person 类,包含了两个成员变量和一个成员方法。通过 new 关键字可以创建 Person 类的实例,并调用其成员方法。