search

Home  >  Q&A  >  body text

node.js - nodejs exports module.exports

nodejs 中经常会看到这样的代码
exports = module.exports = {}
请问 为什么要让 exports = module.exports 呢? 这样做有什么作用呢? 谢谢!!!

巴扎黑巴扎黑2863 days ago600

reply all(1)I'll reply

  • PHPz

    PHPz2017-04-17 15:32:40

    Make this module more purely written.
    module.exports is the interface for the require() method to call the module, and exports can add more methods to the module, and exports returns an instantiation object, pointing to module.exports
    For example, for a constructor Says:
    Person.js

    var Person = function() {
        this.name = 'Samuel';
    }
    
    //通过module.exports
    module.exports = Person;//这里将Person作为模块暴露的接口,传递给require(),使其返回这个Person
    exports.one = 'Shervesi';//这里给Person添加了一个属性,那么通过require()返回的模块也会拥有这个方法

    Use.js

    var P = require('./Person');
    console.log(P.name);//'Samuel'
    console.log(P.one);//'Shervesi',这个属性是Person所不具有的

    Therefore, exports can be understood as the final modification method for the module;
    And module.exports is responsible for exposing an interface for the require() method to call. If module.exports is not declared to point to, then it defaults to Export the object pointed to by exports, such as this scenario:
    Person.js

    var Person = function() {
        this.name = 'Samuel';
    }
    module.exports = 'I am a string';//module.exports被声明指向了一个字符串
    exports.one = 'Shervesi';

    User.js

    var P = require('./Person.js');
    console.log(P);//'I am a string'  //这是module.exports所提供的接口指向的
    console.log(P.one);//这里会出现类型错误,因为负责暴露接口的module.exports已经导出了一个字符串,即是一个常量,因此不能携带one属性,exports所修饰的one属性被‘干掉’。
    

    Summary:

    • module.exports is the arbitration for module export. It decides what to export. It is essentially a return value provided to the require() method, so it can be any basic js Type (including null);

    • exports is an auxiliary method for modifying exported modules, but it is subject to the arbitration of module.exports to determine whether the module can have this attribute.

    reply
    0
  • Cancelreply