3

I have the following:

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

I want to create a sub-module and call a private function from my parent module mod.a. How can I do this while following the best practices of the module pattern?

2 Answers 2

2

A coworker showed me how to do it. It's actually very elegant.

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();
Sign up to request clarification or add additional context in comments.

1 Comment

ah yeah good, also if you havent read this check it out yuiblog.com/blog/2007/06/12/module-pattern, explains what your coworker showed you
1

I would suggest using John Resig's Simple Inheritance code for more object-oriented approach to javascript:

http://ejohn.org/blog/simple-javascript-inheritance/

It allows you to write this:

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 

3 Comments

That might work, but it is not really what I am looking for. I know that I could use inheritance the way you specified it, but I would need to re-write the current module that I have. I also want to follow the module pattern. Anyone?
ah, you use Class. According to MDN IE doesn't support it
@JoãoPimentelFerreira that's why the blog post I linked to contains the implementation of Class so you don't have to rely on browser providing it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.