• 技术文章 >web前端 >H5教程

    exports和module.expors之间有什么区别及联系?

    不言不言2019-01-08 10:50:10转载1409
    本篇文章给大家带来的内容是关于exports和module.expors之间有什么区别及联系?有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

    我们在模块化开发中,必须会用到exports/module.exports这两个玩意导出变量或者函数。因为模块化开发中的每个模块都有自己的模块作用域。
    比如:

    //a.js
    var foo = '苏小猫'
    //b.js
    console.log(foo)

    我们在b.js中是没办法访问到a.js中的foo变量,所以b.js输出的是“undefine”。如果我们想在b.js模块中访问a.js中的foo变量,我们必须在a.js中用exports或者module.exports导出foo变量。
    比如

    //a.js
    var foo = '苏小猫';
    
    module.exports = foo;
    //b.js
    var foo = require('./b.js');
    
    console.log(foo);

    exportsmodule.expors的关系和区别?

    在开发中,我们很纠结到底用exports还是module.exports,其实exports跟module.exports就是一个玩意,exports只是module.exports的一个引用。exports跟module.exports是等价的。我们可以在node里测试一下。

    600505018-5c322b73cf34c_articlex.png

    每个模块最终返回的还是return module.exports;

    在我们平常的理解中导出单个变量或者单个函数就用module.exports;

    module.exports = function(){
        console.log("在你心里种点Bnum")
    }
    
    //我们require之后就会得到一个[Function]

    导出多个变量就用exports;

    exports.name = "苏小猫"
    exports.tree = function(){
        console.log("在你心里种点Bnum")
    }
    //我们require之后就会得到一个对象{name:"苏小猫",tree:[Function]}

    exports和module.exports本身就是一个空对象,exports.xxx就等于在一个对象里面添加东西。

    为什么module.exports导出的是单个?

    因为它本来是一个空对象,module.exports=xxx。现在你重新给它赋值了,所以它只导出这个xxx。

    4256637776-5c3230259349b_articlex.png

    如果给exports(exports={})重新赋值,这时它的意义就不同了;现在的exports,跟module.exports没有了半毛钱的关系了,exports.xxx = xxx;再往里面添加东西已经不会再影响最后返回回来的return module.exports了。

    2419890023-5c3231bf74071_articlex.png

    看,现在age已经不进入最后的return module.exports里面了。

    如果还想继续用exports.xxx,那就得重新再给module.exports赋值给exports。

    809428945-5c32329c6d860_articlex.png

    看,现在又生效了。

    如果很纠结在开发中到底用很exports,还是module.exports,那就忘记exports吧(忘记它,我们不需要备胎,哈哈哈哈)。
    一开始就是说了,exports本身就是module.exports的一个引用。exports能做的module.exports都能做。比如导出多个变量或者函数。

    1203994807-5c3234b2e557c_articlex.png

    以上就是exports和module.expors之间有什么区别及联系?的详细内容,更多请关注php中文网其它相关文章!

    声明:本文转载于:segmentfault,如有侵犯,请联系admin@php.cn删除
    专题推荐:html5 javascript node.js
    上一篇:button按钮和submit按钮有什么区别? 下一篇:HTML5如何使用SVG(代码示例)
    PHP编程就业班

    相关文章推荐

    • nodejs中exports与module.exports的区别详细介绍_基础知识• ImportError: No module named xxx的另外一种原因 module module.exports angular.modul• 详解export default与require和exports,export区别与联系• seaJs中关于exports和module.exports的区别详解• js中的exports详解• node.js和ES6的exports、module.exports使用详解• exports与module.exports使用方法• 深入解析node.js的exports、module.exports与ES6的export、export default

    全部评论我要评论

  • 取消发布评论发送
  • 1/1

    PHP中文网