Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/407.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
javascript设计模式:如何创建子模块和访问父模块私有变量和函数_Javascript_Design Patterns_Module Pattern - Fatal编程技术网

javascript设计模式:如何创建子模块和访问父模块私有变量和函数

javascript设计模式:如何创建子模块和访问父模块私有变量和函数,javascript,design-patterns,module-pattern,Javascript,Design Patterns,Module Pattern,我有以下资料: 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

我有以下资料:

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调用一个私有函数。在遵循模块模式的最佳实践的同时如何做到这一点?

我建议使用John Resig的简单继承代码来实现更面向对象的javascript方法:

它允许您编写以下内容:

var Person = Class.extend({
  init: function(isDancing){
    this.dancing = isDancing;
  }
});
var Ninja = Person.extend({
  init: function(){
    this._super( false );
  }
});

var p = new Person(true);
p.dancing; // => true

var n = new Ninja();
n.dancing; // => false 

一位同事教我怎么做。它实际上非常优雅

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

这可能有用,但这不是我真正想要的。我知道我可以按照您指定的方式使用继承,但是我需要重新编写当前的模块。我还想遵循模块模式。有人吗?啊,你用
Class
。根据MDN,IE不支持it@JoãoPimentelFerreira这就是为什么我链接到的博客文章包含类的实现,所以你不必依赖浏览器来提供它。@JakubKonecki啊,好的,我现在明白了!谢谢啊,是的,很好,如果你还没有读过这篇文章,请检查一下,解释一下你的同事给你看的东西