CNode

module.exports = Hello 和exports.Hello = Hello 什么区别?

Iitfanr发布于12 年前最后回复12 年前6 回复5280 浏览0 收藏

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

查看回复

回复 (6)

R
rapidhere#1·12 年前

比如你的文件叫做hello.js

如果是前者,那么

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

// use function Hello
hello();

如果是后者,那么

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

// use function Hello
hello.Hello();
R
rapidhere#2·12 年前
引用 rapidhere比如你的文件叫做hello.js 如果是前者,那么 如果是后者,那么

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

X
xiuxu123#3·12 年前

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

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

CommonJS中模块的定义:
在模块中,上下文提供require()方法来引入外部模块。对应引入的功能,上下文提供了exports对象用于导
出当前模块的方法或者变量,并且它是唯一导出的出口。在模块中,还存在一个module对象,它代表模块
本身,而exports是module的属性。在Node中一个文件就是一个模块,将方法挂载在exports对象上作为属
性即可一定导出的方式。
I
itfanr#4·12 年前
引用 rapidhere比如你的文件叫做hello.js 如果是前者,那么 如果是后者,那么

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

I
itfanr#5·12 年前
引用 xiuxu123这里借鉴一段深入浅出NodeJS中的一段话:

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

我大概明白了 谢谢你

I
itfanr#6·12 年前
引用 rapidhere比如你的文件叫做hello.js 如果是前者,那么 如果是后者,那么

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

参与回复
登录后即可参与回复。登录