node-模块系统exports与module.exports的区别

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Zckguiying/article/details/86516093

node笔记——exports与module.exports的区别

注意:node每个模块中,exports和module.exports指向同一对象,但每个模块默认返回module.exports。

使用场景:

1、将多个需要导出成员挂载到exports对象中导出,这样在使用导出的成员时,就需要通过对象属性获取

如:var exportsObj = require('./b.js') // 引用b模块导出的多个成员
        console.log(exportsObj.str) // 'hello node'

testa.js

exports.str = 'hello node';

exports.addFunc = function (num1, num2) {
    return num1 + num2
}

module.exports.mulitFunc = function (num1, num2) {
    return num1 * num2
}

testb.js

console.log(exports === module.exports) // true
var exportsObj = require('./b.js') // 引用b模块导出的多个成员
console.log(exportsObj.str) // 'hello node'
console.log(exportsObj.addFunc(1, 2)) // 3
console.log(exportsObj.mulitFunc(3, 2)) // 6

2、导出单个成员,且使得导出的内容本身就是要导出的成员

注意:这里这里使用赋值语句,直接将要导出的成员赋值给每个模块默认返回的module.exports对象。这里千万不能使用exports = 'hello node' 赋值导出,因为node源码中,虽然exports和module.exports指向同一对象,但每个模块默认返回的是module.exports对象,而不是exports,所以,必须给module.exports重新赋值才能达到,导出的就是需要导出成员本身。

testa.js

module.exports = 'hello node';

 testb.js

// 引用b模块导出的字符串,注意,这里不用通过exports对象属性去访问了,直接就是导出的成员本身
var str = require('./b.js')
console.log(str) // 'hello node'

猜你喜欢

转载自blog.csdn.net/Zckguiying/article/details/86516093
今日推荐