How to Add Methods to an Object in JavaScript for HTML5 and CSS3 Programming

Objects in JavaScript have other characteristics besides properties. They can also have methods. A method is simply a function attached to an object. To see what this means, take a look at this example:

 //create the critter
 //from addingMethods.html
 var critter = new Object();
 //add some properties
 critter.name = "Milo";
 critter.age = 5;
 //create a method
 critter.talk = function(){
 msg = "Hi! my name is " + this.name;
 msg += " and I’m " + this.age;
 alert(msg);
 } // end method
 // call the talk method
 critter.talk();

In addition to properties, the new critter has a talk() method. If a property describes a characteristic of an object, a method describes something the object can do.

image0.jpg

Here's how it works:

  1. Build an object with whatever properties you need.

    Begin by building an object and giving it some properties.

  2. Define a method much like a property.

    In fact, methods are properties in JavaScript, but don't worry too much about that; it'll make your head explode.

  3. You can assign a prebuilt function to a method.

    If you created a function that you want to use as a method, you can simply assign it.

  4. You can also create an anonymous function.

    More often, you'll want to create your method right there as you define the object. You can create a function immediately with the function(){ syntax.

  5. The this keyword refers to the current object.

    Inside the function, you may want to access the properties of the object. this.name refers to the name property of the current object.

  6. You can then refer to the method directly.

    After you define an object with a method, you can invoke it. For example, if the critter object has a talk method, use critter.talk() to invoke this method.

  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus
Advertisement

Inside Dummies.com

Dummies.com Sweepstakes

Win $500. Easy.