【问题标题】:How do I get the class name in a mixin?如何在 mixin 中获取类名?
【发布时间】:2014-07-19 18:27:30
【问题描述】:

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

【问题讨论】:

    标签: typescript mixins


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2012-02-11
      • 1970-01-01
      • 2019-11-11
      • 2020-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-24
      相关资源
      最近更新 更多