Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the advantage of using this JavaScript coding pattern to define constructor functions?

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.

like image 353
natlee75 Avatar asked Feb 15 '12 22:02

natlee75


2 Answers

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.

like image 51
Rob W Avatar answered Oct 11 '22 22:10

Rob W


It's effectively a namespace isn't it?

like image 1
crush Avatar answered Oct 11 '22 20:10

crush