2016-08-14 66 views
1

我想了解使用this article的模塊設計模式。如何在模塊化設計模式中嵌套功能?

但我還是不明白幾件事。我想知道的主要事情是如何像我以前那樣「嵌套」功能。 以下是我與我的舊「方法」來實現這一點(我試圖實現):

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". 

所以,出於某種原因,事件對象常量是不是回來了?所以然後我想,我需要回報它。所以我更新了這樣的代碼:

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

我不明白我該如何解決這個問題,任何幫助將不勝感激!謝謝!

回答

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