I tend to write object constructors in the following way:
function Person(name) {
this.name = name;
}
Person.prototype.greet = function () {
alert("Hello! My name is " + this.name + ".");
};
I've noticed a few JavaScript libraries and frameworks adding some extra code around that like so:
var Person = (function () {
function Person(name) {
this.name = name;
}
Person.prototype.greet = function () {
alert("Hello! My name is " + this.name + ".");
};
return Person;
})();
I know what the self-executing anonymous function does and is used for. What I fail to see at the moment is what advantage or benefit this provides when defining a constructor and its prototype.
EDIT #1:
I know the module pattern and its advantages, and use it fairly often in my coding. My mistake in communication was not being clear that my first code sample is not supposed to be in the global scope. I always wrap all of my external JavaScript files in a self-executing anonymous function to enforce local scope on the code.
For instance:
;(function ( window, undefined ) {
var p = function (name) {
this.name;
};
p.prototype.greet = function () {
alert("Hello! My name is " + this.name + ".");
};
window.Person = window.Person || p;
})(window);
The thing is that I've seen the technique displayed in my second code sample used within such an anonymous function.
For instance:
;(function ( window, undefined ) {
var p = (function () {
var q = function (name) {
this.name = name;
};
q.prototype.greet = function () {
alert("Hello! My name is " + this.name + ".");
};
return q;
})();
window.Person = window.Person || p;
})(window);
This is where I'm at a loss for the significance of the technique.