HTML and CSS Reference
Methods are special functions that object-oriented languages use to describe the object's
behavior. Methods are attached to the object with a dot and are only accessible via that
object. Methods, like verbs, are action words that perform some operation on the object.
The cat purrs and the dog barks. The cat object may have a method called sleep() or
play() and the dog object may have a method called sit() or stay() , and both of them
could have a method called eat().
The dot syntax is used to call the methods just as it was used to separate objects from
their properties. When invoked, a set of parentheses are postfixed to the name of the
method. Omitting the parentheses when using a method results in an error.
Methods, like functions, can take arguments, messages that will be sent to the object:
Example 8.3 demonstrates how to create an object and assign properties. But we need
to complete the definition of an object by assigning methods to it. Instead of assigning
a value such as a string or number to the property of an object, you assign a function to
it. Methods let the object do something or let something be done to it. There is little dif-
ference between a function (see Chapter 7, “Functions”) and a method, except that a
function is a stand-alone unit of statements and a method is attached to an object, is
accessed only via the object, and can be referenced by the this keyword. Like functions,
methods also take arguments and can return a value.
var toy = new Object();
// Create the object
toy.name = "Lego";
// Assign properties to the object
toy.color = "red";
toy.shape = "rectangle";
toy.display=printObject; // Function name is assigned as a
// property of the object
document.write("<b>The toy is a " + toy.name + ".<br>");