node.js学习记录 模块module

module模块:

在node中,一个文件就是一个模块。

有一个文件Demo.js

第一行中,Demo.js 加载了同一目录下的 user.js 模块

 
 
let user = require('./User')
console.log(`userame:${user.userName},say ${user.sayHello()}`)
 
 

User.js:

module.exports = {
   userName: 'jack',
   sayHello: function() {
      return 'hello'
   }
}

user.js模块导出了username和sayHello

通过在特殊的 exports 对象上指定额外的属性是私有的,不可被赋予新的值

但是module.exports属性可以被赋予一个新的值(例如函数或对象)。

export和module.export区别:

你改变不了 exports 的引用。准确来说,是*改变后实际导出*的还是 exports 原引用指向的对象。

module.exports 就是用来修复此问题的。

在node中,一个文件就是一个模块。实际上,为了让各个文件里的变量互不干扰,node让每个模块都放在一个闭包中执行,这样实现的模块的隔离。而要让模块间相互联系,就需要暴露变量。

node源码里面,定义了一个Module构造函数,每个模块都是Module的实例,而exports则是Module的一个属性。
function Module(id, parent) {
  this.id = id;
  this.exports = {};
  ...
}
module.exports = Module;

模块的输出就是exports。模块想要对外暴露变量只需要对exports赋值。

// a.js

function foo() {
  console.log('foo');
}

function bar() {
  console.log('bar');
}
想要将这两个函数暴露出去,可以直接使用exports
exports.foo = foo;
exports.bar = bar;
也可以对module.exports赋值
module.exports = {
  foo: foo,
  bar: bar
}
但是不能直接对exports赋值
// 错误
exports = {
  foo: foo,
  bar: bar
}
 简而言之,exports=foo 直接赋值写法会改变exports的引用,它就不再是原来在module上的export了,这种情况就要用module.exports=foo 暴露变量

猜你喜欢

转载自blog.csdn.net/weixin_39173093/article/details/80560416