【学习打卡】第52天 TypeScript(8)

2022/9/26 4:17:10

本文主要是介绍【学习打卡】第52天 TypeScript(8),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

类的静态属性

  • 类的静态属性就是直接挂载到类上的属性,而不是实例或者原型上的属性
  • 在ES6中使用static表示静态属性或者方法
// ES5
function Person(name:string, age: 18) {
  this.name = name;
  this.age = age;
}
Person.attr="move"

// ES6
class Person {
  static attr = 'move';
  constructor(public name: string, public age: number) {}
}

const person = new Person('tz', 18);

类的getter和setter

如下,当想获取或者修改私有属性_name时,不可以在类外修改,可以通过getter获取,通过setter修改

class Person {
  constructor(private _name: string) {}
  get name() {
    return this._name;
  }
  set name(val: string) {
    this._name = val;
  }
}
const person = new Person('tz');

console.log(person.name);  // tz
person.name = 'tom';
console.log(person.name);  // tom

单例

class Person {
  private static instance: Person;

  private constructor() {}

  static getInstance() {
    if (!this.instance) {
      this.instance = new Person();
    }
    return this.instance;
  }
}
const person = Person.getInstance();  

类中的readonly

readonly只能读不能改

class Person {
  public readonly name: string;
  constructor(name: string) {
    this.name = name
  }
}

const person = new Person('tz');
person.name = 'tom';    // 报错: name属性只读不能改
console.log(person.name);  // tz

抽象类

  • 抽象类把其他类共有的属性或者方法抽离出来,用abstract来表示
  • 抽象类不可以实例化,只能被继承
  • 抽象类中也可以有具体属性或者方法的实现
abstract class Geom {
  constructor(public width: string){}
  getType() {
    return "Geom";
  }
  abstract getArea(): number;
}

class Circle extends Geom{
  getArea(): number {
    return 123;
  }
}

class Square{
  getArea(): number {
    return 456;
  }
}


这篇关于【学习打卡】第52天 TypeScript(8)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程