Looking at some JavaScript libraries and other people’s code I’ve seen two common patterns, I don’t know if there is a difference or advantage in using one of them. The patterns look sort of like this:
1.
var app = (function () {
// Private vars
// Module
var obj = {
prop: "",
method: function () {}
};
return obj;
})();
2.
(function () {
// Private vars
// Module
var obj = {
prop: "",
method: function () {}
};
window.app = obj;
})();
Are this patterns the same or do one of them has an advantage or different use than the other?
Thanks in advance.
The second assumes the existence of an object called
windowin the parent scope and assigns a property there.The first one leaves it up to the caller to make the assignment, and does not depend on a
windowbeing defined (which it probably is only inside of a web browser).So, I’d say the first one is definitely better (more self-contained, less environment-dependent).