如何使 JavaScript class 实例成为另一个 class 的实例?

How can I make a JavaScript class instance be instance of another class?

我正在尝试使用 winston 登录我的项目。要创建一个新的记录器,您通常会这样做:

import winston from 'winston';
const logger = winston.createLogger({ ...opts });

但是,我的选项在整个项目中基本相同,除了 label 选项,它将是执行日志记录的模块的名称。我不想在 100 个文件中复制 createLogger 代码,而是想创建一个包装器 class,为 createLogger 提供最常见的选项,并允许用户为 label 给构造函数。 class的实例应该是winston的Loggerclass的实例,也就是createLogger.

的return值

总而言之,我希望能够做到这一点:

import OurLogger from './our-logger';
const fooModuleLogger = new OurLogger('foo'); // full winston Logger instance

我目前在 OurLogger.js 拍摄的最佳照片看起来像:

import winston from 'winston';
export default class {
    constructor(label = 'defaultLabel') {
        const defaultOpts = { ... }

        // I know this part is wrong. But what's the right way?
        this = winston.createLogger({
            label,
            ...defaultOpts
        });
    }
}

您不能分配 this 并且如果不为每个功能位制作包装器方法,class 在这里感觉不对。

为什么不导出一个函数并使用它呢?

export default function OurLogger(label){
    const defaultOpts = { ... }
    return winston.createLogger({
        label,
        ...defaultOpts
    });
}

然后

import OurLogger from './our-logger';
const fooModuleLogger = OurLogger('foo'); // full winston Logger instance