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.
Here's how it works:
Build an object with whatever properties you need.
Begin by building an object and giving it some properties.
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.
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.
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.
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.
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.