如何在mixin类中定义的函数内获取使用mixin而不是mixin类本身名称的类的名称?
要尝试帮助澄清,这是我的代码:
// this function is from TypeScript mixin documentation
function applyMixins(derivedCtor: any, baseCtors: any[]) {
baseCtors.forEach(baseCtor => {
Object.getOwnPropertyNames(baseCtor.prototype).forEach(name => {
derivedCtor.prototype[name] = baseCtor.prototype[name];
});
});
}
class ClassName {
public getClassName(): string {
var funcNameRegex = /function (.{1,})\(/;
var results = (funcNameRegex).exec(this.constructor.toString());
var className = (results && results.length > 1) ? results[1] : '';
return className;
}
}
class ExampleFoo implements ClassName {
getClassName: () => string;
}
applyMixins(ExampleFoo, [ClassName]);
当我实例化ExampleFoo并调用getClassName时,它打印出“ClassName”但我需要它来打印出“ExampleFoo”:
console.log(new ExampleFoo().getClassName()) // => prints "ClassName"
答案 0 :(得分:2)
我建议不要复制构造函数。将函数applyMixins
替换为:
function applyMixins(derivedCtor: any, baseCtors: any[]) {
baseCtors.forEach(baseCtor => {
Object.getOwnPropertyNames(baseCtor.prototype).forEach(name => {
if (name !== 'constructor')
derivedCtor.prototype[name] = baseCtor.prototype[name];
});
});
}