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

这个问题在这里已经有了答案:

  • 在Node.js中,我如何从其他文件“包含”功能? 20个答案
  • Javascript - 在NodeJS中构建助手函数的最佳方式3个答案

  • 你可以这样做:在你喜欢的文件夹中,创建一个像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/

    链接地址: http://www.djcxy.com/p/97017.html

    上一篇: How to collect user defined functions in a liberary in nodjs?

    下一篇: Exporting a module Node.js