node.js 中的 module.exports 与导出 [英] module.exports vs exports in Node.js

查看:32
本文介绍了node.js 中的 module.exports 与导出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Node.js 模块中找到了以下合约:

I've found the following contract in a Node.js module:

module.exports = exports = nano = function database_module(cfg) {...}

我想知道 module.exportsexports 之间有什么区别,以及为什么在这里使用两者.

I wonder what's the difference between module.exports and exports and why both are used here.

推荐答案

设置 module.exports 允许 database_module 函数在 需要时像函数一样被调用.简单地设置 exports 将不允许该功能导出是因为节点导出对象 module.exports 引用.以下代码不允许用户调用该函数.

Setting module.exports allows the database_module function to be called like a function when required. Simply setting exports wouldn't allow the function to be exported because node exports the object module.exports references. The following code wouldn't allow the user to call the function.

以下方法无效.

exports = nano = function database_module(cfg) {return;}

如果设置了 module.exports,以下内容将起作用.

The following will work if module.exports is set.

module.exports = exports = nano = function database_module(cfg) {return;}

控制台

var func = require('./module.js');
// the following line will **work** with module.exports
func();

基本上node.js 不会导出exports 当前引用的对象,而是导出exports 最初引用的对象的属性.尽管 Node.js 确实导出对象 module.exports 引用,但允许您像调用函数一样调用它.

Basically node.js doesn't export the object that exports currently references, but exports the properties of what exports originally references. Although Node.js does export the object module.exports references, allowing you to call it like a function.

他们同时设置 module.exportsexports 以确保 exports 没有引用先前导出的对象.通过设置两者,您可以使用 exports 作为速记,并避免以后出现潜在的错误.

They set both module.exports and exports to ensure exports isn't referencing the prior exported object. By setting both you use exports as a shorthand and avoid potential bugs later on down the road.

使用 exports.prop = true 而不是 module.exports.prop = true 可以节省字符并避免混淆.

Using exports.prop = true instead of module.exports.prop = true saves characters and avoids confusion.

这篇关于node.js 中的 module.exports 与导出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆