在TypeScript中,类是面向对象编程的基本组件之一,用于创建对象和定义其行为。
Class的基本用法
class Animal{
name:string
constructor(name:string){
this.name=name
}
makeSound(){
console.log(this.name,"正在叫")
}
}
const dog = new Animal("小狗")
dog.makeSound()
继承和类型约束
//让Dog类继承Animal类。Dog类同样可以拥有自己的属性和方法
class Dog extends Animal{
age:number
constructor(name:string,age:number){
super(name)
this.age=age
}
eat(){
console.log(this.name,"正在啃骨头")
}
//重写父类方法
makeSound(){
console.log(this.name,"汪汪汪!",this.name,"今年",this.age,"岁了")
}
}
const dog = new Dog("旺财",3)
dog.makeSound()
class的修饰符 readonly private protected public
class Person {
private name: string;
protected age: number;
readonly email: string;
constructor(name: string, age: number, email: string) {
this.name = name;
this.age = age;
this.email = email;
}
}
const person = new Person("小明", 18, "112113114@email.com");
console.log(person.email);// 正确,因为email是公共属性
// person.email = "123123123" // 报错,因为email是只读属性
// console.log(person.name) // 报错,因为name是私有属性
super原理
super关键字用于调用父类的方法。在构造函数中使用super来调用父类的构造函数,确保父类的初始化逻辑被执行。
静态方法
静态方法是通过类本身而不是类的实例调用的。可以直接使用类的名称调用静态方法,而无需创建类的实例。
在静态方法内部,this 关键字指向类本身而不是实例。这使得静态方法能够访问类的静态属性和方法。
class MathOperations {
// 静态属性
static PI: number = 3.14;
// 静态方法
static add(x: number, y: number): number {
return x + y;
}
static multiply(x: number, y: number): number {
return x * y;
}
}
// 调用静态属性
console.log(MathOperations.PI); // 输出: 3.14
// 调用静态方法
console.log(MathOperations.add(2, 3)); // 输出: 5
console.log(MathOperations.multiply(2, 3)); // 输出: 6
get、set
get
和set
用于获取和设置类的属性。
class Rectangle {
private _width: number;
constructor(width: number) {
this._width = width;
}
get width(): number {
return this._width;
}
set width(value: number) {
if (value > 0) {
this._width = value;
} else {
console.error("Width must be greater than 0");
}
}
}
const rect = new Rectangle(5);
console.log(rect.width); // 获取宽度
rect.width = 10; // 设置宽度