【问题标题】:How to collect user defined functions in a liberary in nodjs? [duplicate]如何在节点 js 的库中收集用户定义的函数? [复制]
【发布时间】:2018-02-21 04:40:59
【问题描述】:

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

【问题讨论】:

  • 阅读一些源代码,看看“require(x)”是如何工作的——我想你想做类似的事情。
  • 嗨@thegleep 我是编程新手。谢谢,我现在就去做。

标签: node.js


【解决方案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/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-27
    • 1970-01-01
    • 2016-12-18
    • 1970-01-01
    • 2019-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多