2016-08-14 7 views
1

this articleを使用してモジュールデザインパターンを理解しようとしています。Modular Design Patternで関数をどのように入れ子にすることができますか?

しかし、私はまだいくつかのことを理解していません。私が知りたいことは、以前のように関数を "入れ子にする"方法です。ここ は、私は私の昔の「方法」でこれを達成するために何をしたかである(そして、私が達成しようとしています):

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

さて、これは私の古い「方法」を使用して非常に単純ですが、のような私が言いました、私はモジュールデザインパターンを理解しようとしています。

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

だから何らかの理由でイベントが返されていないオブジェクトリテラル:

これは私がこれまで持っているものでしょうか?だから私は思った、私はそれを返す必要があります。だから私はこのようにコードを更新しました:

私はこれをどのように修正することができます、何か助けになるでしょう理解できません!ありがとうございました!

答えて

3

あなたが好きなあなたのコードを変更することができます。

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(); 
関連する問題