zoukankan      html  css  js  c++  java
  • Node中Exports与module.export的使用与区别

    最近在看《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(' ');
      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所搜集的信息将会被忽略。

  • 相关阅读:
    input上传mp3格式文件,预览并且获取时间
    jquery 页面input上传图后显示
    将String类型的字符串拼接成以逗号分隔的字符输出
    layui select多选下拉显示 以及回显
    input输入框只能输入数字和英文逗号
    电脑开机右下角有小金锁,并且提示一分钟后重启电脑
    修改tomcat控制台的标题
    VC防止程序被多次运行 互斥体方法
    VC中遍历进程并获取进程信息
    VC中遍历目标进程中的模块
  • 原文地址:https://www.cnblogs.com/macoco/p/5398864.html
Copyright © 2011-2022 走看看