As we have seen in Actionscript basic tutorials, we can add a property to objects at runtime, dynamically.
In this tutorial we'll see that you can also dynamically implement methods to objects (in this case the class Object).
The code that we will see is just an object, must be an instance of a dynamic class (in fact, the Object class of Actionscript 3.0 is dynamic), may have properties and methods implemented by us dynamically.
Very useful when you load XML files associating XML data to an object.
Let's see some examples ...
Example 1
Code:
var miles:Object=new Object();
miles.surname="davis";
trace(miles.surname);
miles.getSurname=function():String
{
return this.surname;
}
trace(miles.getSurname());
In this case I implement a property surname to an Object miles.
I can assign the value of such property directly (as the first trace):
Code:
trace(miles.surname);
or by implementing a method ( function ) at the same object that returns value of surname property of miles object.
Code:
miles.getSurname=function():String
{
return this.surname;
}
trace(miles.getSurname());
Note that I used "this" to refer at property surname of the object from inside of the method.
If you do not use "this" Flash finds a global variable named surname ( there is not ) and gives an error.
Example 2
Code:
var miles:Object=new Object();
miles.surname="davis";
miles.sex="male";
miles.music="jazz";
miles.getInfo=function():String
{
return("miles "+this.surname+" is "+this.sex+" and plays "+this.music);
}
trace(miles.getInfo());
In this case I implement a method called getInfo to object miles that returns a concatenation of strings made on the properties of object miles.
Like the following trace does:
Code:
trace(miles.getInfo());
Example 3
Code:
var miles:Object=new Object();
miles.surname="davis";
miles.sex="male";
miles.music="jazz";
miles.skin=function():uint
{
return skinColor("black");
}
var jaco:Object=new Object();
jaco.surname="pastorius";
jaco.sex="male";
jaco.music="fusion";
jaco.skin=function():uint
{
return skinColor("white");
}
function skinColor(s:String):uint
{
var col:uint;
switch(s)
{
case "black":
col=0x000000;
break;
case "white":
col=0xFFFFFF;
break;
case "red":
col=0xFF0000;
break;
case "yellow":
col=0xFFFF00;
break;
}
return col;
}
trace(miles.skin());
trace(jaco.skin());
In this case we have 2 objects ( jaco and miles) and a function (skinColor) reported globally.
The function skinColor is used to add value at methods"skin" of both items.
Indeed methods skin calls the function skinColor passing a value and receiving another (in this case the hex number of colors).
Source files: