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

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

By Andy Harris

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 = "Milo";
 critter.age = 5;
 //create a method = function(){
 msg = "Hi! my name is " +;
 msg += " and I’m " + this.age;
 } // end method
 // call the talk method;

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.


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. 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 to invoke this method.