如何在nodjs中的自由主义中收集用户定义的函数?

时间:2017-09-12 16:09:01

标签: node.js

我有几个functions但我不知道如何在liberary中收集用户定义的函数以在nodeJs项目中重用它们?

1 个答案:

答案 0 :(得分:1)

你可以这样做: 在首选文件夹中,创建一个类似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..);

查看https://www.sitepoint.com/object-oriented-javascript-deep-dive-es6-classes/