javascript设计模式:如何创建子模块以及访问父模块的私有var和函数
作者:互联网
我有以下几点:
mod.a = (function() {
var myPrivateVar = 'a';
function myPrivateFct() {
//do something I will need in my sub-module (mod.a.b)
}
return {
//some public functions
}
})();
mod.a.b = (function() {
// some local vars and functions
return {
mySubModuleFct:function() {
// here I want to call mod.a.myPrivateFct();
}
})();
我想创建一个子模块并从我的父模块mod.a调用一个私有函数.在遵循模块模式的最佳实践的同时如何做到这一点?
解决方法:
一位同事向我展示了如何做.实际上非常优雅.
mod.a = (function() {
var myPrivateVar = 'a';
function myPrivateFct() {
//do something I will need in my sub-module (mod.a.b)
}
return {
b: {
bPublicMethod:function() {
myPrivateFct(); // this will work!
}
}
//some public functions
}
})();
//call like this
mod.a.b.bPublicMethod(); // will call a.myPrivateFct();
标签:module-pattern,javascript,design-patterns 来源: https://codeday.me/bug/20191202/2086560.html