Nov 24, 2008

A better javascript constructor, factory

What is wrong with the following code?

function Animal() {
    this.name = "fred";
    this.say = function() {
        alert("my name is " + this.name);
    };
}

var an = new Animal();
an.say();

What user accidentally, use the it in the following way? The constructor run in the context of global object, or window object. If you design a framework, this is not good thing.

Animal();
say(); //it pollute the  global space
alert(name); //fred

What if user run the following code.

var an = Animal(); //an is undefined because there is no "new" keyword here
an.say();   

Following is using factory to do that. It solves the above problem. First, it will not create side effect like pollute the global space, secondly, object can be created with "new" or without.

function Animal() {
    var r = { name: "fred" }
    r.say = function() {
        alert("my name is " + this.name);
    };
    return r;
}

I call the function with "return" statement , even the statement "return this", factory. function without return is constructor.