How to Build a Reusable Object in Javascript for HTML5 and CSS3 Programming - dummies

How to Build a Reusable Object in Javascript for HTML5 and CSS3 Programming

By Andy Harris

What if you want to build several objects in Javascript with the same definition? JavaScript supports an idea called a constructor, which allows you to define an object pattern and reuse it.

//building a constructor
//from constructor.html
function Critter(lName, lAge){ = lName;
 this.age = lAge; = function(){
  msg = "Hi! my name is " +;
  msg += " and I’m " + this.age;
 } // end talk method
} // end Critter class def
function main(){
 //build two critters
 critterA = new Critter("Alpha", 1);
 critterB = new Critter("Beta", 2); = "Charlie";
 critterB.age = 3;
 //have 'em talk;;
} // end main 

This example involves creating a class (a pattern for generating objects) and reusing that definition to build two different critters. First, look over how the class definition works:

  • Build an ordinary function: JavaScript classes are defined as extensions of a function. The function name will also be the class name. Note that the name of a class function normally begins with an uppercase letter. When a function is used in this way to describe an object, the function is called the object’s constructor. The constructor can take parameters, but it normally does not return any values.

  • Use this to define properties: Add any properties you want to include, including default values. Note that you can change the values of these later if you wish. Each property should begin with this and a period. If you want your object to have a color property, you’d say something like this.color=”blue”.

  • Use this to define any methods you want: If you want your object to have methods, define them using the this operator followed by the function(){ keyword. You can add as many functions as you wish.

The way JavaScript defines and uses objects is easy but a little nonstandard. Most other languages that support object-oriented programming (OOP) do it in a different way than the technique described here. Some would argue that JavaScript is not a true OOP language, as it doesn’t support a feature called inheritance, but instead uses a feature called prototyping.

The difference isn’t all that critical because most uses of OOP in JavaScript are very simple objects like the ones described here. Just appreciate that this introduction to object-oriented programming is very cursory, but enough to get you started.