走进TypeScript之类

说在前面

这里主要将ts中类的使用的一些特性,和其他语言面向对象相通的地方这里就不做多余赘述。

readonly修饰符和参数属性

使用 readonly关键字将属性设置为只读的。 只读属性必须在声明时或构造函数里被初始化。

将只读属性作为构造函数的参数传入。参数属性可以方便地让我们在一个地方定义并初始化一个成员

class Octopus {
    readonly numberOfLegs: number = 8;
    constructor(readonly name: string) {
    }
}

super()

派生类包含的构造函数必须super();

如果构造函数中需要访问this,需要在之前调用super();

执行父类的普通方法,使用super.functionName();

class Animal {
    name: string;
    constructor(theName: string) { this.name = theName; }
    move(distanceInMeters: number = 0) {
        console.log(`${this.name} moved ${distanceInMeters}m.`);
    }
}

class Snake extends Animal {
    constructor(name: string) { super(name); }
    move(distanceInMeters = 5) {
        console.log("Slithering...");
        super.move(distanceInMeters);
    }
}

存取器

存取器可以拦截对类中属性的访问和设置。在set和get方法中对数据进行处理或者过滤。

class Employee {
  _fullName: string;

  set fullName(name: string) {
    console.log("您将要设置_fullName的值:");
    this._fullName = name;
  }

  get fullName(): string {
    console.log("您将要获取_fullName的值:");
    return this._fullName;
  }
}

let employee = new Employee();
employee.fullName = "Bob Smith";
if (employee.fullName) {
  console.log(employee.fullName);
}

静态属性和静态方法

定义:方法或者属性前面添加 static

访问:使用类名来访问

class Grid {
  static origin = { x: 0, y: 0 };
  calculateDistanceFromOrigin(point: { x: number; y: number }) {
    let xDist = point.x - Grid.origin.x;
    let yDist = point.y - Grid.origin.y;
    return Math.sqrt(xDist * xDist + yDist * yDist) / this.scale;
  }
  constructor(public scale: number) {}
}

let grid1 = new Grid(1.0); // 1x scale
let grid2 = new Grid(5.0); // 5x scale

console.log(Grid.origin.x);
console.log(Grid.origin.y);

console.log(grid1.calculateDistanceFromOrigin({ x: 10, y: 10 }));
console.log(grid2.calculateDistanceFromOrigin({ x: 10, y: 10 }));

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值