Reputation: 6289
I am aware of javascript module pattern but I use two types of module patterns and would like to know the difference between them from an architectural perspective.
// PATTERN ONE
var module = (function() {
var _privateVariable = '';
var _privateMethod = function() {
var _this = this;
// private method def
// can use _this._privateVariable
console.log('Inside a private method!');
};
var publicMethod = function() {
var _this = this;
// public method def
// can use _this._privateVariable
// can call _privateMethod();
};
return {
publicMethod: publicMethod
};
})();
// PATTERN TWO
var module = (function() {
var wrapper = {
_privateVariable: '',
_privateMethod: function() {
var _this = this;
// private method def
// can use _this._privateVariable
console.log('Inside a private method!');
},
publicMethod: function() {
var _this = this;
// public method def
// can use _this._privateVariable
// can call _privateMethod();
},
};
return {
publicMethod: wrapper.publicMethod
};
})();
Both these patterns seem to do the same thing for me
Upvotes: 0
Views: 52
Reputation: 397
In fact, there is no difference between the two patterns you've mentioned. Only difference I see is that the second pattern uses wrapper
as an extra variable which can be avoided.
Considering other cases, where you might want to return a complex object rather than the current one, then the second pattern is very useful,
for eg.
var wrapper = {
_privateVariable: '',
_privateMethod: function() {
var _this = this;
console.log('Inside a private method!');
},
publicMethod: function() {
var _this = this;
},
publicMethod2: function() {
var _this = null;
},
publicMethod3: function(default) {
var _this = default;
},
};
return {
publicMethod: wrapper
};
Upvotes: 1