3

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.

RedSandman
  • 153
  • 3
  • 8
  • You don't need `use strict`. – Geuis Mar 23 '19 at 21:05
  • You're exporting an object with two keys (SimpleLogger and DEFAULT_LEVEL); Maybe the constant of log level can belong to SimpleLogger and exporting the class with default. – Cauê Alves Braz Mar 23 '19 at 21:12
  • @Geuis What's wrong with using `"use strict"`? It's generally good practice to include this in your code, as long as it doesn't run at top-level. – kevinji Mar 23 '19 at 21:13
  • @kevinji Actually you're probably right. I have been working exclusively with es6+ for the last few years where strict mode at the module level is enabled and part of the spec. So there's no need for it there. https://stackoverflow.com/questions/18417381/how-is-the-use-strict-statement-interpreted-in-node-js – Geuis Mar 23 '19 at 21:17
  • I've seen 'use strict' just after the class definition rather than at the top of the module. Is there a preference in placement or should I not use it at all? – RedSandman Mar 23 '19 at 21:19
  • @RedSandman If you're in an environment that supports ES6 modules natively, then top of the module is fine. In browsers, I believe `"use strict"` only applies per ` – kevinji Mar 23 '19 at 21:39

1 Answers1

4

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.

richbai90
  • 4,175
  • 3
  • 35
  • 73