Constructors in JavaScript objects

Click Upvote picture Click Upvote · Jul 11, 2009 · Viewed 341.7k times · Source

Can JavaScript classes/objects have constructors? How are they created?

Answer

Nick picture Nick · Jul 12, 2009

Using prototypes:

function Box(color) // Constructor
{
    this.color = color;
}

Box.prototype.getColor = function()
{
    return this.color;
};

Hiding "color" (somewhat resembles a private member variable):

function Box(col)
{
   var color = col;

   this.getColor = function()
   {
       return color;
   };
}

Usage:

var blueBox = new Box("blue");
alert(blueBox.getColor()); // will alert blue

var greenBox = new Box("green");
alert(greenBox.getColor()); // will alert green