HTML5 and CSS3 All-in-One For Dummies
Book image
Explore Book Buy On Amazon

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){
 this.name = lName;
 this.age = lAge;
 this.talk = function(){
  msg = "Hi! my name is " + this.name;
  msg += " and I’m " + this.age;
  alert(msg);
 } // end talk method
} // end Critter class def
function main(){
 //build two critters
 critterA = new Critter("Alpha", 1);
 critterB = new Critter("Beta", 2);
 critterB.name = "Charlie";
 critterB.age = 3;
 //have 'em talk
 critterA.talk();
 critterB.talk();
} // end main 
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.

About This Article

This article is from the book:

About the book author:

Andy Harris taught himself programming because it was fun. Today he teaches computer science, game development, and web programming at the university level; is a technology consultant for the state of Indiana; has helped people with disabilities to form their own web development companies; and works with families who wish to teach computing at home.

This article can be found in the category: