0

In my node project I'm using this basic template structure for a single module

(function() {

  var SimpleModule;
  SimpleModule = (function() {

    function SimpleModule(params) {

      /** private function */
      this.aPrivateFunction = function() {
        return "hidden";
      };

    }

    /** public function */
    SimpleModule.prototype.foo = function() {
      return "bar";
    }

    return SimpleModule;

  })();

  module.exports = SimpleModule;

}).call(this);

so that the caller module will do

var SimpleModule
 ,simpleModuleInstance;

SimpleModule = require('./simplemodule');
simpleModuleInstance = new SimpleModule();
simpleModuleInstance.foo();

Is this a approach formally correct in Node?

7
  • 1
    What's MyModule? Commented Apr 29, 2016 at 12:58
  • 1
    Formally - correctly, but why so complicated? Commented Apr 29, 2016 at 13:08
  • @Nonemoticoner typo fixed thanks. Commented Apr 29, 2016 at 13:21
  • 1
    Unsure as to why you would wrap the module in another "immediately invoked function" when each file is already? Commented Apr 29, 2016 at 13:44
  • 1
    If the module is huge, and you need to use another files, you should use a folder to define your module, creating a package json with a main module, so that you encapsulate everything you need for that module in a folder, and exports just the main module. Then the require is done by folder name. Commented Apr 29, 2016 at 14:49

1 Answer 1

4

How about a simpler approach? Modules are private by default, so everything's already encapsulated except what you export.

function SimpleModule(params) {
  /* Not really private!! */
  this.aPrivateFunction = function() {
    return "hidden";
  };
}

/** public function */
SimpleModule.prototype.foo = function() {
  return "bar";
}

module.exports = SimpleModule;
Sign up to request clarification or add additional context in comments.

1 Comment

@NestorBritez Not really. If you're going to write var instance = new SimpleModule(), you're going to end up with aPrivateFunction on the instance. To get aPrivateFunction as a static method, you'd have to attach it directly to the constructor function: SimpleModule.aPrivateFunction = function() ...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.