TS学习笔记(Five Day)

593 阅读3分钟

TS学习(TS类)

TS类

  • 类的属性和方法:有静态属性,成员属性,构造函数,静态方法,成员方法;
class Greeter {
  // 静态属性
  static cnamestring = "staticCoolFish";
  // 成员属性
  greetingstring;

  // 构造函数 - 执行初始化操作
  constructor(message: string) {
    this.greeting = message;
  }

  // 静态方法
  static getClassName() {
    return "Class name is coolFish";
  }

  // 成员方法
  greet() {
    return "Hello, " + this.greeting;
  }
}

let greeter = new Greeter("coolFish");
console.log(greeter.greet())
//Hello, coolFish

编译后的es5代码

class Greeter {
  // 静态属性
  static cnamestring = "staticCoolFish";
  // 成员属性
  greetingstring;

  // 构造函数 - 执行初始化操作
  constructor(message: string) {
    this.greeting = message;
  }

  // 静态方法
  static getClassName() {
    return "Class name is coolFish";
  }

  // 成员方法
  greet() {
    return "Hello, " + this.greeting;
  }
}

let greeter = new Greeter("coolFish");
console.log(greeter.greet())
//Hello, coolFish
  • 私有字段

    • 每个私有字段以#开头,
    • 每个私有字段名称都唯一地限定于其包含的类
    • 不能在私有字段上使用TS可访问的修饰符
    • 私有字段不能包含类之外的访问,甚至不能被检测
  • 访问器:使用getter和setter来实现数据的封装和有效校验

let key = "IsCoolFish";

class Employee {
  private myNamestring;

  get fullName(): string {
    return this.myName;
  }

  set fullName(newName: string) {
    if (key && key == "IsCoolFish") {
      this.myName = newName;
    } else {
      console.log("Error: Unauthorized update of employee!");
    }
  }
}

let employee = new Employee();
employee.fullName = "coolFish";
if (employee.fullName) {
  console.log(employee.fullName);//coolFish

小结:外层定一个钥匙,每次有值输入的时候,对比钥匙,把握是否允许更改

  • 类的继承
class crab {
  namestring;
  
  constructor(theName: string) {
    this.name = theName;
  }
  
  move(distanceInMeters: number = 0) {
    console.log(`${this.name} '长大了' ${distanceInMeters}cm.`);
  }
}

class newCrab extends crab {
  constructor(name: string) {
    super(name); // 调用父类的构造函数
  }
  
  move(distanceInMeters = 5) {
    console.log("Slithering...");
    super.move(distanceInMeters);
  }
}

let sam = new newCrab("螃蟹小红");
sam.move();//螃蟹小红 '长大了' 5cm.

小结:继承可以理解为螃蟹蜕壳,蜕壳后之前有的,蜕壳后一样有之前的属性,先前定义好的,继承一定要都有,否则就挂了

  • 抽象类:使用abstract关键字声明的类,不能被实例化,只能通过子类继承,然后实例化子类,子类继承要拥有抽象类的所有属性和方法,否则无法继承
abstract class Game {
  constructor(public name: string){}

  // 抽象方法
  abstract say(wordsstring) :void;
}

class Developer extends Game {
  constructor(name: string) {
    super(name);
  }
  
  say(wordsstring): void {
    console.log(`${this.name} '请选择' ${words}`);
  }
}

const leo = new Developer("英雄联盟");
leo.say("英雄"); // 英雄联盟 '请选择' 英雄
  • 类方法重载:和函数重载类似
class game {
  openGame(id?: string) {
    if(typeof id === 'string') {
        console.log(`打开 ${id} 这个游戏`);
    } else {
        console.log(`随机打开一个游戏`);
    }  
  }
}

const productService = new game();
productService.openGame('英雄联盟'); // 打开 英雄联盟 这个游戏
productService.openGame(); // 随机打开一个游戏