Methods
Methods are functions that are associated with objects and are typically used to perform a task or access an object’s data. We invoke methods with the function call operator, ( ), using the dot operator to separate the method name from its object:
objectName.methodName( )
For example:
ball.getArea( ); // Call thegetArea( )method ofball
As with properties, methods are defined for a class and then invoked
on individual object instances. However, before we see how to create
methods within a class, we’re going to bend the rules of good
object-oriented programming and attach a method to an individual
object instance of the built-in Object class.
Once we understand how a single method works on an isolated object,
we’ll apply the concept correctly to a class of our own.
A method is essentially just a function stored in an object property. By assigning a function to an object property, we turn that function into a method of the object:
// Create an object
myObject = new Object( );
// Create a function
function greet ( ) {
trace("hello world");
}
// Now assign greet to the property sayHello
myObject.sayHello = greet;Once a function resides in an object property, we may invoke that function as a method, like this:
myObject.sayHello( ); // Displays: "hello world"
Truth be known, you can also assign a function to an array element (instead of to an object property) and invoke that function using the call operator, like this:
var myList = new Array( ); myList[0] = greet; myList[0]( ); ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access