TypeError:不是构造函数 [英] TypeError: is not a constructor
问题描述
我只是将代码用作有关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屋!