Call a “local” function within module.exports from another function in module.exports?

前端 未结 8 1984
囚心锁ツ
囚心锁ツ 2020-11-30 16:24

How do you call a function from within another function in a module.exports declaration?

app.js
var bla = require(\'./bla.js\');
console.log(bl         


        
相关标签:
8条回答
  • 2020-11-30 16:42

    You can also do this to make it more concise and readable. This is what I've seen done in several of the well written open sourced modules:

    var self = module.exports = {
    
      foo: function (req, res, next) {
        return ('foo');
      },
    
      bar: function(req, res, next) {
        self.foo();
      }
    
    }
    
    0 讨论(0)
  • 2020-11-30 16:42

    Another option, and closer to the original style of the OP, is to put the object you want to export into a variable and reference that variable to make calls to other methods in the object. You can then export that variable and you're good to go.

    var self = {
      foo: function (req, res, next) {
        return ('foo');
      },
      bar: function (req, res, next) {
        return self.foo();
      }
    };
    module.exports = self;
    
    0 讨论(0)
  • 2020-11-30 16:43

    You could declare your functions outside of the module.exports block.

    var foo = function (req, res, next) {
      return ('foo');
    }
    
    var bar = function (req, res, next) {
      return foo();
    }
    

    Then:

    module.exports = {
      foo: foo,
      bar: bar
    }
    
    0 讨论(0)
  • 2020-11-30 16:44

    Change this.foo() to module.exports.foo()

    0 讨论(0)
  • 2020-11-30 16:44

    Starting with Node.js version 13 you can take advantage of ES6 Modules.

    export function foo() {
        return 'foo';
    }
    
    export function bar() {
        return foo();
    }
    

    Following the Class approach:

    class MyClass {
    
        foo() {
            return 'foo';
        }
    
        bar() {
            return this.foo();
        }
    }
    
    module.exports = new MyClass();
    

    This will instantiate the class only once, due to Node's module caching:
    https://nodejs.org/api/modules.html#modules_caching

    0 讨论(0)
  • 2020-11-30 17:00

    You can also save a reference to module's global scope outside the (module.)exports.somemodule definition:

    var _this = this;
    
    exports.somefunction = function() {
       console.log('hello');
    }
    
    exports.someotherfunction = function() {
       _this.somefunction();
    }
    
    0 讨论(0)
提交回复
热议问题