Methods

If you have used another programming language, you might be familiar with concepts such as structures, records, tuples, or forms. An object that only has properties does for you about the same amount as these other common concepts. It's just data. However, objects can also contain methods, as this example shows:

function ordinary_say_hello() { document.write("Hello."); }

function special_print_name()
{
     document.write("My name is: " + this.name);
}

var thing = new Object;

thing.name = "Fred";
thing.say_hello = ordinary_say_hello;
thing.print_name = special_print_name;

thing.say_hello();
thing.print_name();

There are two apparently normal functions here, except that the second one has a mystery variable called this. Near the end of the script, two properties of the thing Object apparently have function names stored into them:

thing.say_hello = ordinary_say_hello;
thing.print_name = special_print_name;

Then right at the bottom, somehow the Object properties began to look like functions:

thing.say_hello();
thing.print_name();

A method is just a function that likes to be inside, or be part of, an object. It does this by letting an object's property track it in the same way that properties and variables can track whole Objects. When the method/function is called (as if it were a property of the Object), the special this variable becomes available inside the method/function. this is a kind of placeholder for whichever Object has called the function, and allows access to all the other properties of the Object the function was called from. It's done like this (no pun intended) so that the function can always get at the properties of the Object it was called from if it needs to, regardless of which Object called it. However, when methods take advantage of the this variable, they can't usually be called as a plain function any more.

Therefore, Objects are really bags of properties and methods. In addition, Javascript objects can have a special prototype property.

© 1997 by Wrox Press. All rights reserved.