I guess using this pattern is the new hotness, but I don’t understand what the advantage is and I don’t understand the scoping implications.
The pattern:
(function(window, document, undefined){
window.MyObject = {
methodA: function() { ... },
methodB: function() { ... }
};
})(window, document)
So I have several questions about this.
Is there a particular advantage to encapsulating an object like this?
Why are window and document being fed in instead of just being accessed normally?
Why the heck is undefined being passed in?
Is attaching the object we’re creating directly to window a particularly good idea?
I’m used to what I’ll call the Crockford style of Javascript encapsulation (because I got it off the Douglas Crockford Javascript videos).
NameSpace.MyObject = function() {
// Private methods
// These methods are available in the closure
// but are not exposed outside the object we'll be returning.
var methodA = function() { ... };
// Public methods
// We return an object that uses our private functions,
// but only exposes the interface we want to be available.
return {
methodB: function() {
var a = methodA();
},
methodC: function() { ... }
}
// Note that we're executing the function here.
}();
Is one of these patterns functionally better than the other? Is the first one an evolution of the other?
Generally to fasten the identifier resolution process, having them as local variables can help (although IMO the performance improvements may be negligible).
Passing the global object is also a widely used technique on non-browser environments, where you don’t have a
windowidentifier at the global scope, e.g.:This is made because the
undefinedglobal property in ECMAScript 3, is mutable, meaning that someone could change its value affecting your code, for example:If you look carefully
undefinedis actually not being passed (there’s no argument on the function call), that’s one of the reliable ways to get theundefinedvalue, without using the propertywindow.undefined.The name
undefinedin JavaScript doesn’t mean anything special, is not a keyword liketrue,false, etc…, it’s just an identifier.Just for the record, in ECMAScript 5, this property was made non-writable…
It’s a common way used to declare global properties when you are on another function scope.