TypeError:不是构造函数 [英] TypeError: is not a constructor

查看:100
本文介绍了TypeError:不是构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是将代码用作有关JavaScript类的学习练习。

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

代码会产生 TypeError:SimpleLogger不是构造函数。该类似乎已导出,可以,但是我无法在main.js文件中实例化该类。

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');

错误在最后一行产生。

推荐答案

您正在导出同时包含 SimpleLogger DEFAULT_LEVEL 的对象因此,要在main.js中使用它,您需要像这样正确引用它

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');

如果只想导出 SimpleLogger ,可以像这样更改您的导出

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

module.exports = SimpleLogger

然后,您可以像在代码中一样要求 SimpleLogger

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

这篇关于TypeError:不是构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆