Visit Mozilla.org

Core JavaScript 1.5 Guide:Creating New Objects:Defining Methods

De MDC

[editar] Defining Methods

A method is a function associated with an object. You define a method the same way you define a standard function. Then you use the following syntax to associate the function with an existing object:

object.methodname = function_name

where object is an existing object, methodname is the name you are assigning to the method, and function_name is the name of the function.

You can then call the method in the context of the object as follows:

object.methodname(params);

You can define methods for an object type by including a method definition in the object constructor function. For example, you could define a function that would format and display the properties of the previously-defined car objects; for example,

function displayCar() {
   var result = "A Beautiful " + this.year + " " + this.make
      + " " + this.model;
   pretty_print(result);
}

where pretty_print is function to display a horizontal rule and a string. Notice the use of this to refer to the object to which the method belongs.

You can make this function a method of car by adding the statement

this.displayCar = displayCar;

to the object definition. So, the full definition of car would now look like

function car(make, model, year, owner) {
   this.make = make;
   this.model = model;
   this.year = year;
   this.owner = owner;
   this.displayCar = displayCar;
}

Then you can call the displayCar method for each of the objects as follows:

car1.displayCar()
car2.displayCar()

This produces the output shown in the following figure.

Image:obja.gif Figure 7.1: Displaying method output