TypeScript类

ES6中也增加了class关键字,TypeScript类的定义和继承

// 类定义
class Person {
  name = 'Brady';
  getName() {
    return this.name;
  }
}

// 子类继承
class Teacher extends Person {
  // 子类方法
  getTeacherName() {
    return 'Teacher';
  }
  // 子类重写父类方法
  getName() {
    // 使用 super 调用父类原有方法
    return super.getName() + '' + this.getTeacherName();
  }
}

// 创建对象
const person = new Person();
const teacher = new Teacher();

console.log(person.getName());
console.log(teacher.getName());
console.log(teacher.getTeacherName());

访问类型: public、protected、private、

  1. public:允许在类的内外调用
  2. protected:允许在类的内部及继承的子类中调用
  3. private:允许在类的内部调用

构造函数 constructor

class Person {
  // 传统
  // public name: string;
  // constructor(name: string) {
  //   this.name = name;
  // }

  // 简化
  constructor(public name: string) {}

  printName(): void {
    console.log(this.name);
  }
}

class Teacher extends Person {
  constructor(public name: string, public age: number) {
    super(name);
  }

  printAge(): void {
    console.log(this.name, this.age);
  }
}

const person = new Person('Brady');
person.printName();
const teacher = new Teacher('Jack', 18);
teacher.printAge();

getter 和 setter 对私有属性的保护

class Person {
  constructor(private _name: string) {}

  get name() {
    return `${this._name} Li`;
  }

  set name(name: string) {
    const realName = name.split(' ')[0];
    this._name = realName;
  }
}

const person = new Person('Brady');
console.log(person.name);
person.name = 'Jack Li';
console.log(person.name);

单例模式示例

/**
 * 单例模式
 */
class Demo {
  private static instance: Demo;

  private constructor(public name: string) {}

  static getInstance() {
    !this.instance ? (this.instance = new Demo('Brady Li')) : '';
    return this.instance;
  }
}

const demo1 = Demo.getInstance();
const demo2 = Demo.getInstance();
console.log(demo1.name);
console.log(demo2.name);

readonly 只读属性

class Person {
  constructor(public readonly name: string) {}
}

const person = new Person('Brady');
console.log(person.name);

抽象类

/**
 * 抽象类
 */
abstract class Geom {
  constructor(public width: number) {}
  getType() {
    return 'Geom';
  }
  // 抽象方法
  abstract getArea(): number;
}

// 圆形类
class Circle extends Geom {
  getArea() {
    return 123;
  }
}

// 方形类
class Square {}

// 三角形类
class Triangle {}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值