exports和module.exports的区别和用法
每一个node.js执行文件,都自动创建一个module对象,同时,module对象会创建一个叫exports的属性,初始化的值是 {}
//foo.js
exports.a = function(){
console.log('a')
}
exports.a = 1
//test.js
var x = require('./foo');
console.log(x.a) //1
exports是引用 module.exports的值。module.exports 被改变的时候,exports不会被改变,而模块导出的时候,真正导出的执行是module.exports,而不是exports
再看看下面:
foo.js
exports.a = function(){ console.log('a') } module.exports = {a: 2} exports.a = 1
test.js
var x = require('./foo'); console.log(x.a) //2
常用的方式:
function View(name, options) { options = options || {}; this.name = name; this.root = options.root; var engines = options.engines; this.defaultEngine = options.defaultEngine; var ext = this.ext = extname(name); if (!ext && !this.defaultEngine) throw new Error('No default engine was specified and no extension was provided.'); if (!ext) name += (ext = this.ext = ('.' != this.defaultEngine[0] ? '.' : '') + this.defaultEngine); this.engine = engines[ext] || (engines[ext] = require(ext.slice(1)).__express); this.path = this.lookup(name); } module.exports = View;
javascript里面有一句话,函数即对象,View 是对象,module.export =View, 即相当于导出整个view对象。外面模块调用它的时候,能够调用View的所有方法。不过需要注意,只有是View的静态方法的时候,才能够被调用,prototype创建的方法,则属于View的私有方法。
foo.js
function View(){ } = function(){ console.log('test') } View.test1 = function(){ console.log('test1') }
test.js
var x = require('./foo'); console.log(x) //{ [Function: View] test1: [Function] } console.log(x.test) //undefined console.log(x.test1) //[Function] x.test1() //test1