Node.js 如何在nodjs的库中收集用户定义的函数?
我有几个Node.js 如何在nodjs的库中收集用户定义的函数?,node.js,Node.js,我有几个函数,但我不知道如何在library中收集用户定义的函数,以便在整个nodeJs项目中重用它们?您可以这样做: 在首选文件夹中,创建一个类似user.js的文件 然后,定义一个类,E6方式: class Users { //if you need a constructor, but it's not mandatory constructor(username,email,otherParamYouNeed){ this.username = username; this.email
函数
,但我不知道如何在library中收集用户定义的函数,以便在整个nodeJs项目中重用它们?您可以这样做:
在首选文件夹中,创建一个类似user.js的文件
然后,定义一个类,E6方式:
class Users {
//if you need a constructor, but it's not mandatory
constructor(username,email,otherParamYouNeed){
this.username = username;
this.email = email;
this.otherParamYouNeed = otherYouNeed
}
//then organize your user functions there
userFunctionThatDoesSomething(){
//do what you need
}
userFunctionThatDoesAnotherThing(){
// do what you need
}
}
//then export the class
module.exports = {Users}
之后,在需要调用这些函数的文件中:
var {Users} = require ('/path/to/user.js');
//if you have constructor in your class
var user = new Users(username,email,otherParamYouNeed);
//if not
var user = new Users;
之后,您将能够在需要该类的文件中使用在该类中声明的函数,如:
user.userFunctionThatDoesSomething(etc..);
看一看阅读一些源代码,看看“require(x)”是如何工作的——我想你也想做类似的事情。嗨@thegleep,我是编程新手。谢谢,我现在就做。