TypeScript Class详解


在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

getset用于获取和设置类的属性。

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; // 设置宽度

  • 13
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值