Two minutes to get the difference between exports and module.exports

the difference between exports and module.exports

  1, analysis

We can be understood from the underlying implementation: a child object exports in the node in each module has its own internal object module, and the module objects, there

    

In the node where and who require the file, whoever get module.exports interface objects

    

 

 

     

We found that by module.exports.xxx each time the export interface member = xxx way a lot of trouble, had to point the way through. 
So node To simplify operation, specializes in providing a variable: exports = module.exports

    That is the underlying implementation module where there is such a code

var exports = module.exports

    Tests are as follows

    

 

 

     

  2, the principle of analytic

exports is a reference to the module.exports

    

 

 

  3, deriving a single module

When exporting a single module, it is necessary to module.exports

    

  4, advanced thinking (object-oriented - reference types)

    Why export a single object can not use exports = xxx; direct assignment definition of export? ? ?

    

 

 

     

 

 

     Schematic: reference data types

    

Next, look at a Questions

    

 

 

     The results for the hello, why?

When the re-assignment to obj1, it will point to a new object, opened up a new memory space, as shown below, this time the two have nothing to do

    

The foregoing analysis can not be used to directly export exports = xxx individual members

    

var exports = module.exports 
similar
var obj1 = obj
here module.exports exports only a reference to it directly exports direct assignment here, and will not affect module.exports, just point to the new object only.
Always remember: the underlying implementation in the final return of the object is module.exports

    

 

  5, re-assignment, dereference

此外,这里要注意:一旦给exports重新赋值,便会失去和module.exports的关联,指向新对象,且后期无法使用。
如下所示

    

    

     

  6、思考2

对上述代码再次修改如下

    

 

 

     结果如下

    

 

   7、思考3

再使用module.exports添加如下

    

 

     

  8、思考4

接下来再做下调整

    

 

     原理如下:

    

 

     换为exports与module.exports

     重定义

这里注意:此时两者已经没有引用关系,最终return的是module.exports所以只需要看module.exports即可

   9、思考5

接着修改代码

    

    

 

   10、思考6

    

 

     

    

  11、小结

复制代码
1、exports为modules.exports的一个引用
2、最后node底层模块导出的是module.exports
3、底层代码
    var module = {
        exports:{...}
    } 
4、exports.name等价于module.exports.name,但node为了方便书写,使用module.exports导出单个成员,本质为将该子对象重新赋值  
5、所以只要给exports赋值,便丢失了module.exports的引用关系,后期便不可用
复制代码

  

 

 

 

 

 

 

.

Guess you like

Origin www.cnblogs.com/jianxian/p/12150940.html