HTML and CSS Reference
In-Depth Information
8.1.4 Methods of the Object
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.
cat.play();
Methods, like functions, can take arguments, messages that will be sent to the object:
dog.fetch("ball");
A JavaScript example:
window.close();
document.write("Hello\n");
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.
EXAMPLE 8.3
<html>
<head><title>User-defined objects</title>
<script type= "text/javascript">
1
var toy = new Object();
// Create the object
2
toy.name = "Lego";
// Assign properties to the object
toy.color = "red";
toy.shape = "rectangle";
3
toy.display=printObject; // Function name is assigned as a
// property of the object
4
function printObject(){
document.write("<b>The toy is a " + toy.name + ".<br>");
 
 
Search WWH ::




Custom Search