TypeScript之类与抽象类

前言:记录一下typeScript中的类,TS中的类与ECMAScript中的类还是有很大区别的!ES6开始引入了类的概念,通过class 关键字定义类,在constructor中定义实例属性等。 比起 ES6中的类,在TS中,多了一些类型定义和private、public等关键字。在TypeScript里,我们可以使用常用的面向对象模式。 基于类的程序设计中一种最基本的模式是允许使用继承来扩展现有的类。

一、类的定义

传统的类为了实现 主业务,抽象类有点类似于 interface

主要是为了抽象,那么其中的抽象方法必须被 继承的类 重新实现

*  1.抽象类可以具体实现,也可以定义抽象方法

 * 2.方法修饰符

 *   public   共有的 任何地方都可以访问到

 *   private  私有的 不能再类的外部使用 子类也不可使用 也就是说内部使用

 *   protected  受保护的 子类中是可以使用的

// 传统的类为了实现 主业务,抽象类有点类似于 interface 
// 主要是为了抽象,那么其中的抽象方法必须被 继承的类 重新实现
abstract class Animal {
    abstract makeSound(): void;
    public move(): void {
        console.log('dog wang---');
    }
    private run(): void {
        console.log('run--');

    }
    protected say(): void {
        console.log('say--');

    }
}

// 继承的子类
class Dog extends Animal {
    constructor() {
        // 需用通过 super 关键字 进行调度
        super();
    }
    makeSound() {
        console.log('cat miao---');

    }
}

const dog = new Dog();
dog.makeSound();
dog.move();

二、抽象类,即可作为一个 实体类 使用,也可以当做一个类型使用,但是不允许创建实例对象

        Tips: 抽象类不允许被 new 调用,也就是不允许创建实例对象,仅作为一个可以被继承的父类。

abstract class Animal {
    
    // 定义一个抽象方法
    // 抽象方法使用 abstract 开头,没有方法体
    // 抽象方法只能定义在抽象类中,子类必须对抽象方法进行重写
    abstract makeSound(): void;

    move(): void {
        console.log('dog wang---');
    }
}

// 继承的子类
class Dog extends Animal {
    constructor() {
        // 需用通过 super 关键字 进行调度
        super();
    }
    makeSound() {
        console.log('cat miao---');

    }
}

const dog = new Dog();
dog.makeSound();
dog.move();


// 类,即可作为一个 实体类 使用,也可以当做一个类型使用

const cat: Dog = new Dog()
cat.makeSound();
cat.move();

const m: Animal = new Dog()
m.move();
m.makeSound();

三、生成私有变量 private 与 # 的区别( 主要是在 build 打包以后生成js的区别 )

  1.用 private 声明的 私有变量

class Demo {
    private num: number;
    constructor() {
        this.num = 20;
    }
}
const n = new Demo();
console.log(n.num)  // 属性“num”为私有属性,只能在类“Demo”中访问。

 private build 生成 js

 2. 用 # 声明的私有变量 ( 主要是使用 WeakMap 来管理 )

class Demo {
    #num: number;
    constructor() {
        this.#num = 20
    }
}
const s = new Demo();
console.log(s.num);

 # build 生成 js

猜你喜欢

转载自blog.csdn.net/weixin_56650035/article/details/122529733
今日推荐