[英]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. 我的问题陈述如下,我有一组匿名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
})();
I want to expose 'getMoney' function to only special child, not every child should have access to getMoney. 我只想向特殊的孩子公开“ getMoney”功能,而不是每个孩子都应该可以使用getMoney。
I believe there should be way to pass some private reference of getMoney function to special child function. 我相信应该有办法将一些getMoney函数的私有引用传递给特殊的子函数。 Any help would be appreciated. 任何帮助,将不胜感激。
Note: I will to rename this question if I find better words to describe it. 注意:如果我找到更好的词来描述这个问题,我将重命名该问题。
You can use a Revealing module pattern to expose a Public API and consume it from other modules. 您可以使用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);
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.