Method (Definition)

A method is an action that can be performed on an object.

Availability:

ECMAScript edition - 2

Functions are implemented in the script interpreter objects and are accessed as methods when they are themselves associated with an object.

Methods are owned by objects. In instance of a class can own some private methods, which it does not share. It can also share methods it inherits from its prototype. Privately owned methods are sometimes called instance methods.

Those functions that are associated with the Global object do not need an object prefix to be used. The Global object is always present and available and in the scope chain and prototype inheritance tree. Therefore the identifiers for those functions can be resolved easily and in your script code, they appear to be like functions in C language.

When you declare functions in your script, as they are constructed they are associated with the Global object and are also available in the same way.

Functions associated with the Math object require the Math object to be cited when they are called. Because they are visibly associated with the object and are called via the object, they are methods.

You can specifically associate one of your own functions with an object other than the Global object. If you do that, then you can refer to the owner object with the variable named 'this'. It is a special variable that is like the 'self' variable in Smalltalk.

Because a function is an object and associating it with your own object is by means of a reference to the function object, you can share function code between several objects.

So, a method is simply a function that is written in a particular way that means it works well when associated with an object and is invoked as the receiver of a message that than a function call.

As soon as you start to use the 'this' variable, then its likely your function is no longer useful as a stand alone function and ought to really be called as a method from that point onwards.

Example code:

   // Function to print an owner object property
   function my_name()
   {
     document.write(this.name);
   }
   // Create a new object instance
   var myObject = new Object;
   // Define the name property for the object
   myObject.name = "Example";
   // Associate the function so it can be used as a method,
   // note that we omit the parentheses
   myObject.my_name = my_name;
   // Call the function via the method interface
   myObject.my_name();
   // Call the function normally
   my_name();

See also:Accessor method, Function, function( ... ) ..., java.util, Member, Property, Statement, this

Cross-references:

ECMA 262 edition 2 - section - 4.3.3

ECMA 262 edition 3 - section - 4.3.3

Wrox Instant JavaScript - page - 30