JavaScript私有内部方法可以访问特定的匿名函数

时间:2016-02-16 03:01:50

标签: javascript

我的问题陈述如下,我有一组匿名的javascript函数如下,其中一个匿名是主人(爸爸函数),他通过附加暴露某些API被其他函数(子函数)使用函数到窗口对象。

//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
   })();

我想将'getMoney'函数暴露给特殊的孩子,而不是每个孩子都应该有权访问getMoney。

我相信应该有办法将getMoney函数的一些私有引用传递给特殊的子函数。任何帮助将不胜感激。

注意:如果我找到更好的词语来描述,我会重命名这个问题。

2 个答案:

答案 0 :(得分:4)

您可以使用Revealing模块模式公开Public API并从其他模块中使用它。



//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);




答案 1 :(得分:0)

调用Revealing Module Pattern,这意味着如果你调用将方法添加到返回对象中,则转为public,这意味着你可以使用,但如果不是你就无法访问。

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