简体   繁体   中英

Node.js require class with constructor parameter

I have a class

class advertHandler {
    constructor(projects) {
        this.projects = projects;
    }

    getProject(name) {
        return this.projects[name];
    }
}


module.exports = new advertHandler(projects);

When I try to use it like this

const advertHandler = require('./advertHandler')(projectsArray);
advertHandler.getProject('test');

And it throws an exception, require is not a function , but without a constructor, everything is fine, so the question is how to use the class constructor with require?

It's not saying require is not a function, it's saying require(...) is not a function. :-) You're trying to call the result of require(...) , but what you're exporting (an instance of advertHandler ) isn't a function. Also note that in advertHandler.js , you're trying to use a global called projects (on the last line); ideally, best to to have globals in NodeJS apps when you can avoid it.

You just want to export the class:

module.exports = advertHandler;

...and then probably require it before calling it:

const advertHandler = require('./advertHandler');
const handler = new advertHandler({test: "one"});
console.log(handler.getProject('test'));

Eg:

advertHandler.js:

class advertHandler {
    constructor(projects) {
        this.projects = projects;
    }

    getProject(name) {
        return this.projects[name];
    }
}

module.exports = advertHandler;

app.js:

const advertHandler = require('./advertHandler');
const handler = new advertHandler({test: "one"});
console.log(handler.getProject('test'));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM