zoukankan      html  css  js  c++  java
  • nodejs exports与module.exports的区别

    exports和module.exports的作用都是将文件模板的方法和属性暴露给require返回的对象进行调用。但是两者有本质的区别,exports的属性和方法都可以被module.exports替代。

    如下代码是一样的:

    exports.name='iwang'
    module.exports.name = 'iwang'

    但是exports不能替代module.exports的方法,所有的exports对象最终都是通过module.exports传递执行的。可以理解exports是给module.exports添加属性和方法的。一开始module.exports是一个空对象。我们使用 require()返回的对象就是module.exports对象。

      文件模板module.js 其实什么都没有写单纯打印module.exports

    console.log(module.exports)

    调用文件模板index.js

    var obj = require('/module')
    console.log(obj)  // {}

    打印出的就是没有属性和方法的空对象。

    看下面文件代码

    module.exports = {
        name:'iwang',
        age:26
    }
    exports.stature = 180
    console.log(module.exports) // { name: 'iwang', age: 26 }

    我们对module.exports 重新定义了这个对象。而不是对module.exportst添加属性和方法。这样做,打断了module.exports和exports的关系。我们使用exports.stature添加了一个stature(身高)的属性,并不管用。当我们使用下面做法,就没有问题。

    module.exports.name = 'iwang';
    module.exports.age = 26;
    exports.stature = 180;
    console.log(module.exports) // { name: 'iwang', age: 26, stature: 180 }

    所以 我们可以理解 一开始 moudle.exports = exports = {},使用require返回的对象是module.exports。所以当我们重新定义module.exports为其他对象的指针。exports和module.exports再也没有半毛钱关系。

    只要大家上面理解红色文字的话,就能区别module.exports和exports的关系了。

  • 相关阅读:
    iOS NSDictionary或NSArray与JSON字符串相互转换
    iOS 如何用Xib画一个Button
    iOS 你不知道的字符串用法
    IOS ScrollView pagingEnabled移动指定偏移
    TableView行缩进 自定义cell时候
    支付宝回调
    微信支付回调
    关于Bundle传递消息
    关于Handler
    ExpandableListView
  • 原文地址:https://www.cnblogs.com/iwang5566/p/6415497.html
Copyright © 2011-2022 走看看