您现在的位置:首页 >> 前端 >> 内容

typescript Mixin混合的官方实例

时间:2018/6/29 12:01:11 点击:

  核心提示:官方实例// Disposable Mixinclass Disposable {isDisposed: boolean;dispose() {this.isDisposed = true;}}// ...

官方实例

// Disposable Mixin
class Disposable {
    isDisposed: boolean;
    dispose() {
        this.isDisposed = true;
    }

}

// Activatable Mixin
class Activatable {
    isActive: boolean;
    activate() {
        this.isActive = true;
    }
    deactivate() {
        this.isActive = false;
    }
}

class SmartObject implements Disposable, Activatable {
    constructor() {
        setInterval(() => console.log(this.isActive + " : " + this.isDisposed), 500);
    }

    interact() {
        this.activate();
    }

    // Disposable
    isDisposed: boolean = false;
    dispose: () => void;
    // Activatable
    isActive: boolean = false;
    activate: () => void;
    deactivate: () => void;
}
applyMixins(SmartObject, [Disposable, Activatable]);

let smartObj = new SmartObject();
setTimeout(() => smartObj.interact(), 1000);

////////////////////////////////////////
// In your runtime library somewhere
////////////////////////////////////////

function applyMixins(derivedCtor: any, baseCtors: any[]) {
    baseCtors.forEach(baseCtor => {
        Object.getOwnPropertyNames(baseCtor.prototype).forEach(name => {
            derivedCtor.prototype[name] = baseCtor.prototype[name];
        });
    });
}

单单看官方的示例可能不是很好理解,要知道typescript是不支持多继承的,smartObj 当new 这个对象时,心中已经很清楚的知道他具备Disposable, Activatable中的方法和属性,但是在smartObj并未实现这些Disposable, Activatable,所以就声明出来欺骗typescript的检查的,从而可实现多继承的功能,在Disposable, Activatable中也可相互调用,因此在smartObj 他们已经在同一类中,混合也可用于对特别复杂的类进行按功能拆分,需注意类型的一致性;

Tags:TY YP PE ES 
作者:网络 来源:米斯特尔曾的博客