[英]JavaScript private inner method give access to specific anonymous function
我的问题陈述如下,我有一组匿名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函数的私有引用传递给特殊的子函数。 任何帮助,将不胜感激。
注意:如果我找到更好的词来描述这个问题,我将重命名该问题。
您可以使用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);
这就是所谓的“显示模块模式”,这意味着如果您调用将方法添加到返回对象中(此方法公开),则意味着您可以使用,但不能访问。
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.