Javascript Node.js 需要带有构造函数参数的类

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42553700/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:15:14  来源:igfitidea点击:

Node.js require class with constructor parameter

javascriptnode.js

提问by MyMomSaysIamSpecial

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?

并且它抛出一个异常,require is not a function但是没有构造函数,一切都很好,所以问题是如何使用带有 require 的类构造函数?

回答by T.J. Crowder

It's not saying requireis not a function, it's saying require(...)is not a function. :-) You're trying to callthe 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.

不是说require不是函数,而是说require(...)不是函数。:-) 您正在尝试调用的结果require(...),但是您导出的( 的实例advertHandler)不是函数。另请注意,在 中advertHandler.js,您正在尝试使用全局调用projects(在最后一行);理想情况下,最好在可以避免的情况下在 NodeJS 应用程序中使用全局变量。

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

E.g.:

例如:

advertHandler.js:

advertHandler.js:

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

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

module.exports = advertHandler;

app.js:

应用程序.js:

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