gpt4 book ai didi

typescript - 我如何在mixin中获取类名?

转载 作者:搜寻专家 更新时间:2023-10-30 21:11:18 25 4
gpt4 key购买 nike

如何在混合类中定义的函数中获取使用混合类的类的名称,而不是混合类本身的名称?

为了帮助澄清,这是我的代码:

// 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())//=> 打印“ClassName”

最佳答案

我建议不要复制构造函数。将函数 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];
});
});
}

关于typescript - 我如何在mixin中获取类名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24843628/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com