Search code examples
javascriptmodule-pattern

Objects literal and 'this' in submodule pattern


Im working in a sub-module pattern code. Want to create sub-modules with objects literals, the problem is this for the objects inside the sub-module is MODULE and not my object literal. Any idea?

var MODULE.sub = (function () {

   var myObject = {

       key: value,

       method: function () {
           this.key // this = MODULE and not MyObject... :(
       }

   };

   return myObject.method;

}(MODULE));

Solution

  • Solved... just return a function in MODULE.sub calling the public method. I don't know if is the best approach

    var MODULE.sub = (function () {
    
       var myObject = {
    
           key: value,
    
           method: function () {
               this.key // this = myObject :)
           }
    
       };
    
       return function () {
            myObject.method();
        }
    
    }(MODULE));