提出这个问题是因为我不完全理解打字稿“ strictPropertyInitialization”及其带来的影响。 不确定是否在我的SmartObject类中立即初始化功能Activate(),dispose()和deactivate(),有人可以帮助并解释正确的方法吗?
// Disposable Mixin
class Disposable {
isDisposed:boolean
constructor() {
this.dispose = this.dispose
}
dispose() {
this.isDisposed = true;
}
}
// Activatable Mixin
class Activatable {
constructor(public isActive:boolean) { }
activate() {
this.isActive = true;
}
deactivate() {
this.isActive = false;
}
}
class SmartObject implements Disposable, Activatable {
// Disposable
isDisposed: boolean = false;
dispose: () => void;
// Activatable
isActive: boolean = false;
activate: () => void;
deactivate: () => void;
constructor() {
setInterval(() => console.log(this.isActive + " : " + this.isDisposed), 500);
this.dispose = this.dispose;
this.activate = this.activate;
this.deactivate = this.deactivate;
}
interact() {
this.activate();
this.dispose()
}
}
applyMixins(SmartObject, [Disposable, Activatable]);
let smartObj = new SmartObject();
setTimeout(() => smartObj.interact(), 1000);
const test = new Disposable();
setTimeout(() => { console.log(test.isDisposed) },2000)
////////////////////////////////////////
// In your runtime library somewhere
////////////////////////////////////////
function applyMixins(derivedCtor: any, baseCtors: any[]) {
baseCtors.forEach(baseCtor => {
Object.getOwnPropertyNames(baseCtor.prototype).forEach(name => {
Object.defineProperty(derivedCtor.prototype, name, Object.getOwnPropertyDescriptor(baseCtor.prototype, name));
});
});
}
有关打字稿中OOP的任何提示和技巧?