module.exports = Hello 和exports.Hello = Hello 什么区别?
发布于 10 年前 作者 itfanr 4202 次浏览 最后一次编辑是 8 年前

function Hello(){ var name ; this.setName = function(thyName){ name = thyName ; }; this.sayHello = function(){ console.log(‘Hello’+name); }; }

6 回复

比如你的文件叫做hello.js

如果是前者,那么

var hello = require('hello.js');

// use function Hello
hello();

如果是后者,那么

var hello = require(`hello.js`);

// use function Hello
hello.Hello();

才看到Hello是一个构造函数。。。注释写的有问题,不过应该不影响理解。

这里借鉴一段深入浅出NodeJS中的一段话:

Node中的模块系统主要借鉴CommonJS的Modules规范,Node能以一种比较成熟的姿态出现,离不开CommonJS规
范的影响。  

CommonJS中模块的定义:
在模块中,上下文提供require()方法来引入外部模块。对应引入的功能,上下文提供了exports对象用于导
出当前模块的方法或者变量,并且它是唯一导出的出口。在模块中,还存在一个module对象,它代表模块
本身,而exports是module的属性。在Node中一个文件就是一个模块,将方法挂载在exports对象上作为属
性即可一定导出的方式。

@rapidhere module.exports = Hello 这种情况 必须文件名是Hello.js吧?

@xiuxu123 exports是module的属性;在Node中一个文件就是一个模块,也可以将方法挂载在exports对象上作为属 性导出

我大概明白了 谢谢你

@rapidhere 一个文件中最多有一句module.exports 吧?

回到顶部