Gerrit Luimstra Gerrit Luimstra - 3 months ago 7
Javascript Question

How can I nest functions in the Modular Design Pattern?

I am trying to understand the Module Design Pattern using this article.

But I still don't understand a few things. The main thing I want to get to know, is how to "nest" functions like I did before.
Here is what I did to achieve this with my old "method" (And what I am trying to achieve):

var ContentEditor = ContentEditor || {};
ContentEditor.events = {
sayHi: function(){
alert("Hi!");
}
}
ContentEditor.events.sayHi();


Now, this is pretty simple using my old "method", but like I said, I am trying to understand the Module Design Pattern.

This is what I have so far:

var ContentEditor = (function(){
// the nested "library"
var events = {
sayHi: function(){
alert();
}
}
})();
ContentEditor.events.sayHi(); // this returns "Cannot read property 'events' of undefined".


So for some reason the events object literal is not returned? So then I thought, I need to return it. So I updated the code like so:

var ContentEditor = (function(){
// Notice the return here
return {
var events = {
sayHi: function(){
alert();
}
}
}
})();
ContentEditor.events.sayHi(); // This returns "Unexpected identifier".


I do not understand how I can fix this, any help will be appreciated! Thank you!

Answer

You can modify your code like:

var ContentEditor = (function() {

  // Create the events object here
  var events = {

    // Our first private function
    sayHi: function() {
      alert('Hi!');
    },

    // One more private function inside the events object
    sayBye: function() {
      alert('Bye!');
    }
  }

  // Create some public functions here
  // and pass the private functions references to it
  return {
    sayHi: events.sayHi,
    sayBye: events.sayBye
  }
})();

// Call the public functions here
ContentEditor.sayHi();
ContentEditor.sayBye();