Nov 24, 2008

A better javascript constructor, factory

What is wrong with the following code?

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

var an = new Animal();

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.

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

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 " +;
    return r;

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

No comments:

Post a Comment