Passing arguments to require (when loading module)

后端 未结 3 1322
情书的邮戳
情书的邮戳 2020-11-29 16:03

Is it possible to pass arguments when loading a module using require?

I have module, login.js which provides login functionality. It requires a database connection,

3条回答
  •  迷失自我
    2020-11-29 16:28

    I'm not sure if this will still be useful to people, but with ES6 I have a way to do it that I find clean and useful.

    class MyClass { 
      constructor ( arg1, arg2, arg3 )
      myFunction1 () {...}
      myFunction2 () {...}
      myFunction3 () {...}
    }
    
    module.exports = ( arg1, arg2, arg3 ) => { return new MyClass( arg1,arg2,arg3 ) }
    

    And then you get your expected behaviour.

    var MyClass = require('/MyClass.js')( arg1, arg2, arg3 )
    

提交回复
热议问题