来自工厂设计而非类的JavaScript模块

时间:2018-10-09 23:39:40

标签: javascript module factory

我最近尝试学习JavaScript,并且试图了解工厂设计模式。这样做我遇到了这个问题。

我有一个简单的记录器类,可以将其导出为模块,该类扩展了事件模块类。

const EventClass = require('events');

class Logger extends EventClass { 
    printSomething(something) {
        console.log(something);    
        this.emit('logged', { context: 'not implemented' });
    }
}    
module.exports = Logger;

它在这里捕获了事件

const EventClass = require('events');
const Logger = require('./logger');

logger.on('logged', (arg) => {
    console.log('Listener called', arg);
});
logger.printSomething('something');

我如何能够使用工厂设计模式重新创建此方案,而不是使该类从events类扩展?

这是我的镜头:

const EventClass = require('events');
const eventObject = new EventClass();

const Log = function () {
    const log = {};
    log.eventObject; // HERE I TRY TO SET THE eventObject TO THE LOG
    log.printSomething = (something) => {
        console.log(something);
        eventObject.emit('logged', { context: 'not implemented' });
    }
    return log;
}

const loggerObject = Log();
module.exports = loggerObject;

const EventClass = require('events');
const logger = require('./logger');
logger.eventObject.on('logged', (arg) => {
    console.log('Listener called', arg);
});
logger.printSomething('something');

我认为在函数范围内创建事件类的实例,就可以做到logger.eventObject。而且我不知道如何使其成为嵌套对象。

Stacktrace:

TypeError: Cannot read property 'on' of undefined
    at Object.<anonymous> (C:\Users\Jonas\Desktop\min hjemmeside\index.js:3:20)
    at Module._compile (module.js:653:30)
    at Object.Module._extensions..js (module.js:664:10)
    at Module.load (module.js:566:32)
    at tryModuleLoad (module.js:506:12)
    at Function.Module._load (module.js:498:3)
    at Function.Module.runMain (module.js:694:10)
    at startup (bootstrap_node.js:204:16)
    at bootstrap_node.js:625:3

导出模块后如何使eventObject可访问?

1 个答案:

答案 0 :(得分:1)

我通常不回答自己的问题-但我找到了解决方案。

const EventClass = require('events');
let eventObject = new EventClass();

const Log = function () {
    const log = {};
    log.eventObject = new EventClass(); //I ended up assigning the eventObject like this
    log.printSomething = (something) => {
        console.log(something);
        eventObject.emit('message is logged', { context: 'not implemented' });
    }
    return log;
}
module.exports = Log;

如果深入解释为何这样做与以前相反,我仍然会接受答案。