Pradeep
Pradeep

Reputation: 6603

JavaScript private inner method give access to specific anonymous function

My problem statement is as follows, I have set of anonymous javascript functions as follows, one of the anonymous is main guy( Papa function), he exposes certain kind of API to be used by other function (Child functions) by attaching function to window object.

//Example papa function

   (function(window,console){
          console.log('I am Papa'); 
          //I do other stuff too
          window.PAPA= {
              getAdvice : function() {
                      console.log('Work hard');
              },
              getHelp : function() {
                      console.log('Give Help');
              },
              getMoney : function() {
                      console.log('1$');
              }
          }
   })(window,console);

//Example Child function
(function(){
          console.log('I am Child'); 
          if ( !PAPA )
               return;

          //use PAPA functions as required
   })();

I want to expose 'getMoney' function to only special child, not every child should have access to getMoney.

I believe there should be way to pass some private reference of getMoney function to special child function. Any help would be appreciated.

Note: I will to rename this question if I find better words to describe it.

Upvotes: 0

Views: 41

Answers (2)

yamitrvg12
yamitrvg12

Reputation: 19

It is call Revealing Module Pattern, that mean if you call add the method into the return object, this turn public, that mean you can use but if not you couldn't access.

var PapaModule = ( function( window, undefined ) {

    function getAdvice() {
        console.log('Work hard');
    }

    function getHelp() {
        console.log('Give Help');
    }

    function getMoney() {
        console.log('1$');
    }

    // explicitly return public methods when this object is instantiated
    return {
        getMoney : getMoney,
        someOtherMethod : myOtherMethod
    };

} )( window );


//  example usage
PapaModule.getMoney(); // console.log Work hard
PapaModule.getHelp(); // undefined
PapaModule.getAdvice(); // undefined

Upvotes: 0

Mauricio Poveda
Mauricio Poveda

Reputation: 66

You can use a Revealing module pattern to expose a Public API and consume it from other modules.

//Example papa function

var papa = (function(){
  console.log('I am Papa'); 
  
  //I do other stuff too
  getAdvice : function() {
    console.log('Work hard');
  },
  getHelp : function() {
    console.log('Give Help');
  },
  getMoney : function() {
    console.log('1$');
  }
  
  return {
      getAdvice: getAdvice,
      getHelp: getHelp,
      getMoney: getMoney
  }
})();


//Example Child function
var child = (function(papa){
  console.log('I am Child'); 

  //use PAPA functions as required
  papa.getAdvice();
})(papa);

Upvotes: 4

Related Questions