类与对象
TypeScript作为JavaScript的超集,在JavaScript的基础上增加了类型系统,使得代码更加健壮。在TypeScript中,面向对象编程(OOP)是非常重要的一个概念。我们先从最基本的类和对象开始。
类的定义
在TypeScript中,使用class关键字来定义一个类。类包含属性和方法,属性是类的数据,方法是对数据的操作。
class Person {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
sayHello(): void {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}
}
在上面的代码中,我们定义了一个Person类,包含name和age两个属性,以及一个sayHello方法。
实例化对象
使用new关键字可以创建类的实例,也就是对象。
const person = new Person('Alice', 25);
person.sayHello(); // 输出:Hello, my name is Alice and I am 25 years old.
继承
继承是面向对象编程中非常重要的一个概念,它允许我们创建一个基于另一个类的新类,并继承它的属性和方法。
基类与派生类
在TypeScript中,使用extends关键字来实现继承。
class Employee extends Person {
department: string;
constructor(name: string, age: number, department: string) {
super(name, age);
this.department = department;
}
getDepartment(): string {
return this.department;
}
}
在上面的代码中,我们定义了一个Employee类,它继承自Person类,并添加了一个新的属性department。
多态
多态是指同一个方法在不同的类中具有不同的行为。在TypeScript中,多态可以通过继承和重写方法来实现。
class Manager extends Employee {
sayHello(): void {
console.log(`Hello, my name is ${this.name}, I am a manager in the ${this.department} department.`);
}
}
在上面的代码中,Manager类继承自Employee类,并重写了sayHello方法。
封装与访问修饰符
封装是面向对象编程中的另一个重要概念,它用于隐藏类的内部实现,只暴露必要的接口。
访问修饰符
在TypeScript中,使用访问修饰符来控制属性和方法的访问级别。
public:公共的,可以在类外部访问。protected:受保护的,可以在类内部和子类中访问。private:私有的,只能在类内部访问。
class Person {
private _name: string;
constructor(name: string) {
this._name = name;
}
get name(): string {
return this._name;
}
set name(value: string) {
this._name = value;
}
}
在上面的代码中,_name属性被标记为private,因此只能在Person类内部访问。我们通过get和set方法来访问和修改_name属性。
TypeScript面向对象实战案例
现在,我们通过一个实战案例来展示如何使用TypeScript面向对象编程。
案例描述
假设我们正在开发一个在线商店项目,需要实现商品类(Product)和订单类(Order)。
商品类(Product)
class Product {
public id: number;
public name: string;
public price: number;
constructor(id: number, name: string, price: number) {
this.id = id;
this.name = name;
this.price = price;
}
}
订单类(Order)
class Order {
public id: number;
public products: Product[];
public total: number;
constructor(id: number, products: Product[]) {
this.id = id;
this.products = products;
this.total = products.reduce((sum, product) => sum + product.price, 0);
}
}
实战案例代码
const product1 = new Product(1, 'Laptop', 1000);
const product2 = new Product(2, 'Smartphone', 500);
const order = new Order(1, [product1, product2]);
console.log(`Order ID: ${order.id}`);
console.log(`Total: $${order.total}`);
通过以上实战案例,我们可以看到TypeScript面向对象编程的强大之处。使用类和对象可以让我们更好地组织代码,提高代码的可读性和可维护性。
总结
本文通过介绍TypeScript中的类、继承、封装等面向对象编程概念,以及一个实战案例,帮助编程小白轻松上手TypeScript面向对象编程。在实际开发中,合理运用面向对象编程思想,可以使代码更加清晰、高效。
