Methods - assigning functions to objects
Objects may contain functions as well as variables. A function assigned to an object is called a method of that object.
Like a constructor function, a method refers to its variables with the this operator. The following fragment is an example of a method that computes the area of a rectangle.
function rectangle_area()
{
return this.width * this.height;
}
Because there are no parameters passed to it, this function is meaningless unless it is called from an object. It needs to have an object to provide values for this.width and this.height.
A method is assigned to an object as the following lines illustrates.
joe.area = rectangle_area;
The function will now use the values for height and width that were defined when we created the rectangle object joe.
Methods may also be assigned in a constructor function, again using the this keyword. For example, the following code:
function rectangle_area()
{
return this.width * this.height;
}
function Rectangle(width, height)
{
this.width = width;
this.height = height;
this.area = rectangle_area;
}
creates an object class Rectangle with the rectangle_area method included as one of its properties. The method is available to any instance of the class:
var joe = Rectangle(3,4);
var sally = Rectangle(5,3);
var area1 = joe.area;
var area2 = sally.area;
This code sets the value of area1 to 12, and the values of area2 to 15.