Mixins
TypeScript Mixins
创建Mixins
为了创建一个
下面是一个声明合并的例子:
interface Car {
steering: number;
tyre: number;
}
interface Car {
exhaustOutlet: number;
}
// contains properties from both Car interfaces
const BMW: Car = {
steering: 1,
tyre: 4,
exhaustOutlet: 2,
};
现在我们了解了这两个
class Block {
name = "";
length = 0;
breadth = 0;
height = 0;
constructor(name: string, length: number, breadth: number, height: number) {
this.name = name;
this.length = length;
this.breadth = breadth;
this.height = height;
}
}
接下来,创建基类所要扩展的类。
class Moulder {
moulding = true;
done = false;
mould() {
this.moulding = false;
this.done = true;
}
}
class Stacker {
stacking = true;
done = false;
stack() {
this.stacking = false;
this.done = true;
}
}
创建一个接口,合并与你的基类(Block)同名的预期类。
interface Block extends Moulder, Stacker {}
这个新接口的定义与我们之前创建的
创建函数
要创建一个函数来连接两个或多个类声明,我们将使用
function applyMixins(derivedCtor: any, constructors: any[]) {
constructors.forEach((baseCtor) => {
Object.getOwnPropertyNames(baseCtor.prototype).forEach((name) => {
Object.defineProperty(
derivedCtor.prototype,
name,
Object.getOwnPropertyDescriptor(baseCtor.prototype, name) ||
Object.create(null)
);
});
});
}
前面的函数迭代了
applyMixins(Block, [Moulder, Stacker]);
TypeScript Mixin example
let cube = new Block("cube", 4, 4, 4);
cube.mould();
cube.stack();
console.log(
cube.length,
cube.breadth,
cube.height,
cube.name,
cube.moulding,
cube.stacking
);
在这里,我们将
虽然有其他方法来创建
常用案例
让我们来看看你可能会遇到的或想要考虑的
Handling multiple class extension
class Moulder {
moulding = true;
done = false
mould() {
this.moulding = false;
this.done = true;
}
}
class Stacker {
stacking = true;
done = false
stack() {
this.stacking = false;
this.done = true;
}
}
class Block extends Moulder, Stacker{
constructor() {
super()
}
}
在这个例子中,