mercredi 16 mai 2018

Use javascript module inside an object

I'm asking a question:

Imagine I have a javascript module (using revealing module pattern) and I want to use it inside some prototype methods of an object. What will be the best way on your opinion to do it? I have currently two ideas in mind: - Pass the global module to the constructor of the object and keep it in an object property (this.myModule...) - Use the module from the prototype method directly as global variable

Let me explain you the situation with a small example:

I have file1.js containing the module :

var myModule = (function(){ function doSomething(){...} return {doSomething: doSomething}})()

To use this module, which of the two options is the best for you? Or maybe you have a better option to propose? I can't use requirejs nor any libraries to ease the modularity and dependency management of my application. Also, I can't change the existing architecture.

// Option 1
function myObject(myModule){
  ...
  this._myModule = myModule;
}

myObject.prototype.doAnotherThing = function(){
  ...
  this._myModule.doSomething();
}
var test = new myObject(myModule);

// Option 2
function myObject(){
  ...
}

myObject.prototype.doAnotherThing = function(){
  ...
  myModule.doSomething();
}
var test = new myObject();

I'm really interested by having your point of view.

Thanks a lot in advance,

Remi

Aucun commentaire:

Enregistrer un commentaire