• 两个示例来说明node.js中module.exports与exports的区别(在VS Code下设置断点运行)


    在VS Code下设置断点运行

    exports1.js

     1 // -------- node.js core --------
     2 
     3 var module = {
     4     exports: {
     5 
     6     }
     7 };
     8 
     9 exports = module.exports;
    10 
    11 // -------- 下面正常写代码 --------
    12 
    13 exports.name = 'Alan';
    14 exports.test = function () {
    15     console.log('hi')
    16 };
    17 
    18 // 给导出的对象添加属性,直接这样就好了
    19 console.log(module.exports) // { exports: { name: 'Alan', test: [Function] } }
    20 
    21 // A.赋值给exports不会改变module.exports
    22 // exports = {
    23 //     name: 'Bob',
    24 //     add: function (a, b) {
    25 //         return a + b;
    26 //     }
    27 // }
    28 // B.赋值给exports.name会改变module.exports
    29 exports.name = 'Bob' // 赋值给exports不会改变module.exports, 赋值给exports.name会改变module.exports
    30 // 不过 ① exports 是一个引用,直接赋值给它,只是让这个变量等于另外一个引用
    31 console.log(exports) // { name: 'Bob', add: [Function] }
    32 // 并不会修改到导出的对象
    33 console.log(module.exports) // A. { exports: { name: 'Alan', test: [Function] } }
    34                             // B. Object {name: "Bob", test: }
    35 
    36 module.exports = {
    37     name: 'Bob',
    38     add: function (a, b) {
    39         return a + b;
    40     }
    41 }
    42 
    43 // ∵① 所以 只有通过 module.exports 才能真正修改到 exports 本身
    44 console.log(module.exports) // { exports: { name: 'Bob', add: [Function] } }
    45 console.log(exports)

    exports2.js

    var module = {
        exports: {
            name: "我是module的exports属性"
        }
    };
    var exports = module.exports;  
    //exports是对module.exports的引用,也就是exports现在指向的内存地址和module.exports指向的内存地址是一样的
    
    console.log(module.exports);    //  { name: '我是module的exports属性' }
    console.log(exports);   //  { name: '我是module的exports属性' }
    
    
    exports.name = "我想改一下名字";
    
    
    console.log(module.exports);    //  { name: '我想改一下名字' }
    console.log(exports);   //  { name: '我想改一下名字' }
    //看到没,引用的结果就是a和b都操作同一内存地址下的数据
    
    
    //这个时候我在某个文件定义了一个想导出的模块
    var Circle = {
        name: "我是一个圆",
        func: function (x) {
            return x * x * 3.14;
        }
    };
    
    exports = Circle;
    //看清楚了,Circle这个Object在内存中指向了新的地址,所以exports也指向了这个新的地址,和原来的地址没有半毛钱关系了
    
    console.log(module.exports);    //  { name: '我想改一下名字' }
    console.log(exports);   // { name: '我是一个圆', func: [Function] }

    参考:①https://cnodejs.org/topic/52308842101e574521c16e06

       ②https://www.zhihu.com/question/26621212

  • 相关阅读:
    Unsafe(转载) 规格严格
    MySQL 中文 规格严格
    2007“奥普迪杯”开放式实时在线辞典系统设计大赛
    2007“奥普迪杯”开放式实时在线辞典系统设计大赛
    2007年个人回忆与总结
    蔡学镛:2008编程语言走势解盘
    用scanf实现gets的功能
    2007年个人回忆与总结
    用scanf实现gets的功能
    初学入门:如何有效编写软件的75条建议
  • 原文地址:https://www.cnblogs.com/stefango/p/9176279.html
Copyright © 2020-2023  润新知