最近在看《node开发实战详解》时有写疑问,所以自己就整理了一些资料。下面是node4.*的官方api文档(http://nodejs.cn/doc/node_4/modules.html#modules_module_exports),我有点看不懂,就拉出node.10*的官方api(https://nodejs.org/dist/v0.10.9/docs/api/modules.html#modules_module_exports)。
module.exports与exports的介绍
module.exports与exports都是将函数或者是方法暴露出去,require的时候进行调用,但是2者是有区别的。以下是代码:
//ex.js
exports='danhuangmode';
//mex.js
module.exports='danhuangmode';
//call_ex_mex.js
var ex=require('./ex');
var mex=require('./mex');
console.log(ex);
console.log('\n');
console.log(mex);
执行结果:
引用exports提供方法,输出是为一个对象,引用module.exports提供方法,输出为字符串。
exports内部提供接口,在外部引用时之间的关系如何?
exports内部处理暴露方法,是如何处理的,看如下代码:
var string='this is in exports.js';
function ex_fn () {
console.log('this in funtion ex_fn');
}
var exobj={
str1:"str1 exobj",
exobjfn: function () {
console.log("in function");
}
};
exports.string=string;
exports.ex_fn=ex_fn;
exports.exobj=exobj;
exports=exobj;
调用代码:
var ex=require('./ex');
console.log(ex.string);
console.log(ex.ex_fn);
console.log(ex.exobj);
console.log(ex);
结果显示:
exports提供的所有接口,直接调用导出实例化的接口对象,会显示接口对象中所有提供的类型、函数、对象以及对象中的方法和对象。
module.exports对外提供接口如何处理?
//mex.js
var ex_fn= function () {
console.log('this in funtion ex_fn');
}
module.exports=ex_fn;
调用代码mex.js:
//引用mex.js
var ex=require('./mex');
ex();
console.log(ex);
执行结果为:
直接将函数作为返回。
再看下面一个例子:
var person={
name :"person's name",
age :20,
getAge: function () {
return this.age;
}
}
module.exports = person;
调用的代码:
var person=require('./modulex');
console.log(person.name);
console.log(person.age);
console.log(person.getAge());
console.log(person);
显示的结果为:
返回为一个json对象,可以直接调用内部的函数、属性。
module.exports 与exports是什么关系?
module.exports = 'personname';
exports.name=function () {
console.log('this is person name');
}
调用 的脚本:
var person=require('./person');
console.log(person);
console.log(person.name);
执行结果:
personname
undefined
结果:
其实真正的接口是module.exports,exports是一个辅助工具。最终返回到是module.exports,而不是exports。
当module.exports没有任何属性和方法,exports将收集的所有信息都传递给module.exports,如果module.exports已经具有了属性和方法,exports所搜集的信息将会被忽略。
运维网声明
1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网 享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com