TypeError: is not a constructor

蓝咒 提交于 2019-12-13 14:30:39

问题


I'm just using the code as a learning exercise regarding JavaScript classes.

The code produces a "TypeError: SimpleLogger is not a constructor". The class seems to be exported Ok but I can't instantiate it in the main.js file.

I've reduced the code to just show the issue. I was wondering if anyone can spot the problem. Thanks.

// In simplelogger.js
"use strict";
class SimpleLogger {
    constructor(level) {
        this.level = level || DEFAULT_LEVEL;
    }

    // .... other methods
}

const DEFAULT_LEVEL = 'info';

module.exports = {
    SimpleLogger,
    DEFAULT_LEVEL
}

// In main.js
"use strict";
const SimpleLogger = require('./simplelogger.js');

let log = new SimpleLogger('info');

The error is produced in the last line.


回答1:


You're exporting an object containing both SimpleLogger and DEFAULT_LEVEL therefore to use it in main.js you need to reference it properly like so

const SimpleLogger = require('./simplelogger.js').SimpleLogger;
let log = new SimpleLogger('info');

If you only want to export SimpleLogger you can change your export like so

module.exports = SimpleLogger

Then you can require SimpleLogger as you do in your code.



来源:https://stackoverflow.com/questions/55318369/typeerror-is-not-a-constructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!