但是我仍然不明白一些事情。我想了解的主要事情是如何像以前一样“嵌套”功能。这是我使用旧的“方法”(也是我想要实现的)来实现此目的的方法:
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".
我不知道如何解决此问题,我们将不胜感激!谢谢!
您可以像下面那样修改您的代码:
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();
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句