Question

I have some Javascript code spread over multiples files, yet I want to facilitate minification with an IFFE. Some methods must remain public.

Wikipedia suggests the implementation of accessors:

var counter = (function(){
  var i = 0;

  return {
    get: function(){
      return i;
    },
    set: function( val ){
      i = val;
    },
    increment: function() {
      return ++i;
    }
  };
}());

Unfortunately, declaring these from return is not easy when such functions are declared in multiple files.

Is the following a proper solution? If not, what is?

var counter = (function(){

  var i = 0;

  // Import js file 1...
  this.get = function(){ return i; };

  // Import js file 2...
  this.set = function( val ){ i = val; };

  // Import js file 3...
  this.increment = function() { return ++i; };

  return this;

}());

P.S.: I want to be able to perform the following calls:

counter.get();
counter.set(33);
counter.increment();
Was it helpful?

Solution

It seems like the pattern that you are interested in is something like this:

//file 1
var xy = (function (that) {
    that.prop1 = 1;
    return that;
}(xy || {}));


//file2
var xy = (function (that) {
    that.prop2 = 2;
    return that;
}(xy || {}));

This will result in a single global object xy that has two properties:

xy = {
    prop1: 1,
    prop2: 2
};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top