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
- Is there a significant difference in using either of them?
- Should one of these patterns be avoided?
- Is there a better way to use either of them?
asked Dec 2, 2017 at 15:13
Dinesh Pandiyan
6,3393 gold badges36 silver badges50 bronze badges
1 Answer 1
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
};
answered Dec 2, 2017 at 15:32
Krishna Modi
3973 silver badges13 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-js
publicMethod()instead of "exporting" it.var _this = this;is not meaningful in either of your patterns. You should just refer to the variables directly (in the first snippet), or to properties ofwrapper(in your second snippet).