Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

CommonJS规范 #3

Open
Kelichao opened this issue Nov 26, 2016 · 0 comments
Open

CommonJS规范 #3

Kelichao opened this issue Nov 26, 2016 · 0 comments

Comments

@Kelichao
Copy link
Owner

Kelichao commented Nov 26, 2016

CommonJS规范(主要用于Node.js环境)

阮一峰博客

阮一峰教程

  • seaJS也使用了CommonJS规范,浏览器不兼容CommonJS的根本原因,在于缺少四个Node.js环境的变量。
  • global
  • module
  • exports
  • require

global

global相当于是浏览器中的window,对外暴露的全局对象,
在他之上挂载的对象在任何作用域中都能访问到

require

引入模块包的对象
如果我想要在我的项目文件主入口处引入别的js包
那么只需要 var  package1 = require('模块名/模块地址')

module

这个对象比较复杂,挂载了不少属性与方法,其中一个就是exports。
而且module.exports才是模块公开的接口,每个模块
(在node中每个js文件就是一个独立的模块,不需要包装)
都会自动创建一个module对象,对象有一个modules的属性,
module下挂载的一个名叫module.exports的对象,用于导出模块。

exports

exports与 module.exports 的关系,为什么也可以通过exports对象来公开接口呢?

         为了方便,模块中会有一个exports对象,和module.exports指向同一个变量,
(指向的地址为同一个)所以我们修改exports对象的时候也会修改module.exports对象,
(类似引用对象)。这样我们就明白网上盛传的module.exports对象不为空的时候
exports对象就自动忽略是怎么回事儿了,因为module.exports通过赋值方式
已经和exports对象指向的变量不同了,exports对象怎么改和module.exports对象没关系了。

理解exports

//exports变量
//为了方便,Node为每个模块提供一个exports变量,指向module.exports。
//这等同在每个模块头部,有一行这样的命令。

var exports = module.exports;

// 在加载模块之前就有的
module.exports=exports = {};
// 加载了模块......

module.exports=new Object();// 重写对象

exports=xxx;//和new Object没有关系了,最后返回module.exports,所以改动都无效了
// 所以统一用 module.exports才是最稳妥的
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant