I've seen there are two ways of implementing the modular pattern in javascript:
- Using object literals
- Using self executed functions (returning object)
I usually see more often the use of functions rather than objects for this purpose.
Is there any advantage on it besides the one of hiding some private functions from outside?
Using self executed functions: (returning object)
var Module = (function () {
var self = this;
self.init = function () {
self.someMethod();
};
self.someMethod = function () {
$('#demo').on('click', function(){
self.privateMethod();
});
};
self.privateMethod = function () {
console.log("aaa");
};
return {
someMethod: someMethod,
init:init
};
})();
Module.init();
Using object literals
var Module = {
init: function(){
this.someMethod();
this.self = this;
},
someMethod: function(){
var self = this;
$('#demo').on('click', function(){
console.log(this.id);
self.anotherMethod();
});
},
anotherMethod: function(){
console.log("aa");
}
};
Module.init();
Aucun commentaire:
Enregistrer un commentaire