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.
The second method, the module pattern, is more portable. Notice that you can name Person
to anything you want.
At the first method, you would have to keep track of every occurrence of Person
, and be careful to not accidentally delete part of the method when copying the constructor+prototype to another project.
The second method has an additional advantage: You can use local/temporary/throw-away variables which can be used to dynamically define constants/methods/properties on the namespace.
It's effectively a namespace isn't it?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With