12.4. Adding Custom Methods to an Object Instance
Problem
You want to add custom methods to an object.
Solution
Assign a function definition (or a reference to one) to a custom property of an object that is already instantiated.
Discussion
You can add functionality to objects (instances of a class) by assigning new methods to them. First, define a function. Then store a reference to the function in a custom property of the object. That is, the definitions of an object’s methods are stored as properties of the same object.
This example stores a function in the custom property
methodProp:
myObject = new Object( );
myObject.methodProp = function ( ) {
trace("Hello World");
};The preceding example assigns a method to an object
using
an anonymous function. However, you can also use
object properties to store references to named
functions. The following example stores a reference to the
named function, myMethodFunction( ), in the
property myMethod:
// Define a named function.
function myMethodFunction ( ) {
trace(this.myProperty);
}
// Create a new object. You can assign custom methods to any kind of object (movie
// clip, array, etc.), but this example uses a generic object of the Object class. myObject = new Object( ); // Create a custom property on the object. This is not necessary, per se, but we use // it here to illustrate that when a function is called as a method of an object, the // function has access to all the properties of that object by means of // self-references (using the ...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