前言:例子中 ts 和 js 中 class 做对比,方便更深刻的理解
- // ts
- class Person {
- // public 默认, 公开的
- public name: string;
- // private 私有属性, 实例和继承不可访问, 本身可以访问
- private age: number;
- // protected 受到保护的, 实例不能访问, 继承和本身可以访问
- protected sex: string;
- // static 静态属性, 只能类本身访问
- static adress: string;
- // readonly 只读, 不能修改
- readonly love: string;
-
- constructor(name: string, age: number, sex: string, love: string) {
- this.name = name;
- this.age = age;
- this.sex = sex;
- this.love = love;
- }
- }
-
- // js
- class Person {
- // static 静态属性, 只能类本身调用
- static age = 18;
- constructor(name) {
- this.name = name;
- }
- }
- // ts
- class Person {
- name: string;
- constructor(name: string) {
- this.name = name;
- }
- }
- class SuperPerson extends Person {
- age: number;
- constructor(name, age) {
- super(name);
- this.age = age;
- }
- }
-
- // js
- class Person {
- constructor(name) {
- this.name = name;
- }
- }
- class SuperPerson extends Person {
- constructor(name, age) {
- super(name);
- this.age = age;
- }
- }
当一个存取器只带有 get 却不带有 set 时,它会被自动推断为 readonly。
- // ts
- class Person {
- name: string;
- constructor(name: string) {
- this.name = name;
- }
- get nameL(): string {
- return `${this.name}.length`;
- }
- set nameL(value: string) {
- this.name = `my newName is ${value}`;
- }
- }
-
- // js
- class Person {
- constructor(name) {
- this.name = name;
- }
-
- get nameL() {
- return this.name.length;
- }
-
- set nameL(value) {
- this.name = `my newName is ${value}`;
- }
- }
抽象类只能作为其他派生类的基类使用,抽象类不能被实例化,它具有如下特点:
- 抽象类可以包含成员的实现细节,且抽象类必须用 abstract 声明
- 抽象类里不含方法体的方法称为抽象方法,使用 abstract 声明,抽象方法必须被子类实现(抽象方法必须使用 abstract 关键字声明,且可以包含访问修饰符)
- // ts
- abstract class Person {
- name: string;
- constructor(name: string) {
- this.name = name;
- }
- // 抽象方法: 必须被子类实现
- abstract sayHi(): void;
- }
- class Student extends Person {
- study: string;
- constructor(name: string, study: string) {
- super(name);
- this.study = study;
- }
- sayHi() {
- console.log("hi");
- }
- }
-
- // js 中没有抽象类
上一章:前端 TS 快速入门之二:接口
下一章:前端 TS 快速入门之四:函数