• ts的混入


    ts的混入

    刚接触混入(mixins),很容易跟合并(merge)搞混淆.看了官方文档的解释才弄明白

    merge

    For the purposes of this article, “declaration merging” means that the compiler merges two separate declarations declared with the same name into a single definition. This merged definition has the features of both of the original declarations. Any number of declarations can be merged; it’s not limited to just two declarations.

    merga是将名字相同的声明合并到1个definition里,然后这个definition拥有所有declaration的特征.

    typeScript只能单继承,不能多继承。为了实现多继承的效果,ts提供了一些写法.❗mixins不是功能,而是概念.

    “Real” Mixins with JavaScript Classes

    A mixin is an abstract subclass; i.e. a subclass definition that may be applied to different superclasses to create a related family of modified classes.

    Gilad Bracha and William Cook, Mixin-based Inheritance

    下面给出如何在typeScript中实现mixins的写法.

    单继承mixins

    TypeScript: Documentation - Mixins的例子

    class Sprite {
        name = "";
        x = 0;
        y = 0;
    
        constructor(name: string) {
            this.name = name;
        }
    }
    
    // To get started, we need a type which we'll use to extend
    // other classes from. The main responsibility is to declare
    // that the type being passed in is a class.
    
    type Constructor = new (...args: any[]) => {};
    
    // This mixin adds a scale property, with getters and setters
    // for changing it with an encapsulated private property:
    
    function Scale<TBase extends Constructor>(Base: TBase) {
        return class Scaling extends Base {
            // Mixins may not declare private/protected properties
            // however, you can use ES2020 private fields
            private _scale = 1;
    
            set scale(scale: number) {
                this._scale = scale;
            }
    
            get scale(): number {
                return this._scale;
            }
        };
    }
    
    // Compose a new class from the Sprite class,
    // with the Mixin Scale applier:
    const EightBitSprite = Scale(Sprite);
    
    const flappySprite = new EightBitSprite("Bird");
    flappySprite.scale = 0.8
    // (property) Scaling.scale: number
    console.log(flappySprite.scale); // output:0.8
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43

    这里给2个function设置了setget修饰符,让scale(scale: number)scale()变成了属性。如果只设置get那么_scale就会变成readonly.

    2.混入实现多继承

    因为typeScript不支持多继承,所以这里要用implements来实现.

    class MyName {
        name: string
        constructor(name: string) {
            this.name = name
        }
        getName(): string {
            return this.name
        }
    }
    
    class MyAge {
        age: number
        constructor(age: number) {
            this.age = age
        }
        setAge(age: number): void {
            this.age = age
        }
    }
    
    class Jack implements MyName,MyAge{
        name: string
        getName!: () => string
        age: number
        setAge!: (age: number) => void
        constructor(name:string,age:number){
            this.name = name
            this.age = age
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30

    因为是implements所以是需要实现class里的属性的.这里我选择不实现所以用!使其可以为undefined通过编译.

    上面的class准备好后下面才是mixins.

    function applyMixins(derivedCtor: any, baseCtors: any[]) {
        baseCtors.forEach(baseCtor => {
            Object.getOwnPropertyNames(baseCtor.prototype).forEach(name => {
                if(name != 'constructor'){
                    derivedCtor.prototype[name] = baseCtor.prototype[name];
                }
            });
        });
    }
    
    applyMixins(Jack,[MyName,MyAge])
    let jack = new Jack('J4ck',0)
    console.log(jack.getName()); // output:J4ck
    
    console.log(jack.age); // output:0
    jack.setAge(23)
    console.log(jack.age); // output:23
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    可以看到Jack类获得了MyNameMyAge的所有特征.

  • 相关阅读:
    每日汇评:黄金将测试1935美元的200日移动均线
    二叉树——遍历:按层次非递归遍历、先序非递归、先中后序递归遍历二叉树的链表结构【C语言,数据结构】(内含源代码)
    OSPF的接口网络类型
    Java游戏核心架构之通信架构
    UE5 ChaosVehicles载具 实现大漂移 (连载四)
    【硅谷甄选】P44 element-plus 含有多个子菜单的菜单的折叠字体图标溢出
    Hbase(二)进阶
    搜索引擎-01-概览
    (undone) 如何计算 Hessian Matrix 海森矩阵 海塞矩阵
    Python中的协程、线程和进程
  • 原文地址:https://blog.csdn.net/qq_40710190/article/details/133381234