Exporting Objects with the Exports Object

后端 未结 4 1512
野趣味
野趣味 2021-02-02 14:36

Say I have one .js file containing a javascript object. I want to be able to access that object and all of its functionality from another .js file in t

4条回答
  •  深忆病人
    2021-02-02 14:52

    This is the way I create modules:

    myModule.js

    var MyObject = function() {
    
        // This is private because it is not being return
        var _privateFunction = function(param1, param2) {
            ...
            return;
        }
    
        var function1 = function(param1, callback) {
            ...
            callback(err, results);    
        }
    
        var function2 = function(param1, param2, callback) {
            ...
            callback(err, results);    
        }
    
        return {
            function1: function1
           ,function2: function2
        }
    }();
    
    module.exports = MyObject;
    

    And to use this module in another JS file, you can simply use require and use your object as normal:

    someFile.js

    var myObject = require('myModule');
    
    myObject.function1(param1, function(err, result) { 
        ...
    });
    

提交回复
热议问题