14 类与继承 🏫之构造函数与属性

在之前的章节中,我们探讨了 TypeScript 中类的基本用法,包括如何定义类、创建实例以及类中的方法。在本章节中,我们将深入研究构造函数与属性的具体实现,以便更好地理解类的工作机制。

构造函数

构造函数是一个特殊的方法,用于初始化类实例的属性。当你创建一个类的实例时,构造函数会被自动调用。构造函数的名称与类名相同,并且没有返回值。它的主要作用是设置实例的状态。

示例

我们来看一个简单的示例,定义一个 Person 类并添加一个构造函数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Person {
name: string;
age: number;

// 构造函数
constructor(name: string, age: number) {
this.name = name; // 使用传入的参数初始化属性
this.age = age;
}

introduce(): string {
return `Hello, my name is ${this.name} and I am ${this.age} years old.`;
}
}

// 创建实例
const person1 = new Person("Alice", 30);
console.log(person1.introduce()); // 输出: Hello, my name is Alice and I am 30 years old.

在上面的代码示例中,我们定义了一个 Person 类,它有两个属性:nameage。通过构造函数,我们能够在创建 Person 实例的时候传递这些属性的初始值。

属性

类的属性是在类中描述对象状态的变量。它们可以是任意类型,包括基本类型和其他对象类型。

属性的访问修饰符

TypeScript 支持三种属性访问修饰符:

  • public:公共属性,类的外部可访问,默认修饰符。
  • private:私有属性,只能在类的内部访问。
  • protected:受保护属性,类内部和子类可以访问。

以下是使用访问修饰符的示例:

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 Employee {
public id: number;
private salary: number;
protected department: string;

constructor(id: number, salary: number, department: string) {
this.id = id;
this.salary = salary;
this.department = department;
}

// 公共方法
displayInfo(): string {
return `Employee ID: ${this.id}, Department: ${this.department}`;
}

// 私有方法,类内部调用
private calculateAnnualSalary(): number {
return this.salary * 12;
}
}

const employee1 = new Employee(1, 5000, "Engineering");
console.log(employee1.displayInfo()); // 输出: Employee ID: 1, Department: Engineering
// console.log(employee1.salary); // Error: Property 'salary' is private and only accessible within class 'Employee'.

在这个例子中,我们定义了一个 Employee 类,其中有三个属性,分别使用了不同的访问修饰符。我们可以通过 displayInfo 方法访问公共属性,但无法在外部访问私有属性 salary

小结

在本章中,我们介绍了构造函数的作用以及如何定义和使用类的属性,同时探讨了 TypeScript 的访问修饰符的最佳实践。构造函数提供了一种简便的方法来初始化类的实例,而属性则定义了对象的状态。理解这两者是更深入学习面向对象编程的基础。

在下一章中,我们将进一步探讨继承与多态,以及如何利用这些特性来增强代码的重用性与扩展性。

14 类与继承 🏫之构造函数与属性

https://zglg.work/typescript-zero/14/

作者

IT教程网(郭震)

发布于

2024-09-14

更新于

2024-09-14

许可协议

分享转发

交流

更多教程加公众号

更多教程加公众号

加入星球获取PDF

加入星球获取PDF

打卡评论