很多人看一些包里面的代码时常会看到:
exports = module.exports = ...
对于module.exports的说明:
The module.exports object is created by the Module system.
Sometimes this is not acceptable; many want their module to be an instance of some `class`.
To do this assign the desired export object to module.exports
官方给的例子:
示例文件1:
//a.js
var EventEmitter = require('events').EventEmitter;
module.exports = new EventEmitter();
引用文件2:
//b.js
var a = require('./a');
//a.js
module.exports.job = "fe";
exports.name = function(){
console.log('yaochun');
};
//b.js
var a = require('./a');
console.log(a); //{ job: 'fe', name: [Function] }
1、module.exports在前:
//a.js
module.exports.job = "fe";
exports.job = "pd";
//b.js
var a = require('./a');
console.log(a); //{ job: 'pd' }
2、exports在前:
//a.js
exports.job = "pd";
module.exports.job = "fe";
//b.js
var a = require('./a');
console.log(a); //{ job: 'fe' }
注释:这个时候,最好还是采用exports.props,节省字符而且避免歧义。
module.exports = exports
当模块被require的时候,node用c++实现了包裹,会变成:
(function (exports, require, module, __filename, __dirname) {
//...
});
而且require方法返回的是module.exports对象的指向。
//a.js
module.exports = function test(){
};
exports.name = function(){
console.log('yaochun');
};
//b.js
var a = require('./a');
console.log(a); //[Function: test]
上面的情况,exports指向了一个,而module.exports指向另一个,看到b里面还是module.exports定义的
扫码关注w3ctech微信公众号
学习
共收到1条回复