首页 > 解决方案 > 为什么他们在导出数据或事件时不使用 Object?

问题描述

我正在尝试通过书籍和 Todos 之类的示例来了解节点并做出反应。

但我从未见过他们在想要导出数据时使用 Object。

他们为什么不使用它?

只要我使用Object,导出时不需要添加数据或事件。

例子

const insertUser = async (userData) => {
 ***
};

const loginAction = async (where) =>{
    ***
}

const checkDuplicationID = async (userId) => {
    ****
}
//you should add the event when you export event whenever events are added. 
module.exports = { loginAction, insertUser, checkDuplicationID }

我的意见

let userActions = {}

userActions.insertUser = async (userData) => {
    ****
};

userActions.loginAction = async (where) =>{
   ****
}

userActions.checkDuplicationID = async (userId) => {
   ****
}

//you don't need to add the event when you export event.
module.exports = { userActions }

如果我使用 Object 有什么问题吗?

标签: node.jsexpresskoa

解决方案


使用对象没有问题,在javascript中,几乎所有东西都是对象。你可以像这样导出方法

module.exports = {
  insertUser: async (userData) => {
    // logic
  },
  loginAction: async (where) => {
    // logic
  },
  checkDuplicationID: async (userId) => {
    // logic
  }
}

您可以导入/要求该模块并在其他模块中使用它

// import or require
const myMethods = require('./path/filename');

// call the method
myMethods.insertUser();
myMethods.loginAction();
myMethods.checkDuplicationID();

推荐阅读