如何在mixin中获取类名?

时间:2014-07-19 18:27:31

标签: typescript mixins

如何在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"

1 个答案:

答案 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];
    });
  });
}