Lately I've been learning JS module pattern and I've seen at least 3-4 ways to create function expressions with public and private properties. My problem is I don't understand what's the best difference between them and what's the best approach / best practice.
The syntax on the 4 examples below are different but all of are invoked the same way. Can you explain me what's the difference between them?
Example A - I declare function func() and return only the method/function name.
var funcA = function() {
var hi = "hello";
function bye() {
return 'bye';
}
function hello() {
return hi;
}
return {
hello: hello
}
}();
Example B - here I declare foo = function() and return only the method/function name.
var funcB = function() {
var hi = "hello";
var bye = function() {
return 'bye';
}
var hello = function() {
return hi;
}
return {
hello: hello
}
}();
Example C - here I declare foo = function() inside the return
var funcC = function() {
var hi = "hello";
var bye = function() {
return 'bye';
}
return {
hello: function() {
return hi;
}
}
}();
Example D - same as prev but all the function is wrapped in ()
.
var funcD = (function() {
var hi = "hello";
var bye = function() {
return 'bye';
}
return {
hello: function() {
return hi;
}
}
})();
In each case if I want to call hello() I just write funcX.hello()
and all of them return "hello"
But all of them are created by different ways. What's the correct one? If there is a correct way.
Thanks.