View Single Post
Nutrox's Avatar Nutrox Nutrox is offline Super Moderator 17 Creative Assets 2006-11-05 #7 Old  
006 - Prototype Functions
Last edited by Codemonkey : 2006-11-11 at 03:00.
 
Prototype functions can be used if you want to add functions to Flash's core classes such as String, Array, Number, and so on. When you create a prototype function, all instances of the prototyped class will be able to access the new function.

For example, let's say that you want to be able to reverse any of your strings at any time in your movie. To do that you would add a prototype function to the String class like this:

ActionScript Code:
  1. String.prototype.reverse = function() {
  2.         var a = this.split("");
  3.         a.reverse();
  4.         return a.join("");
  5. };
Now that the new function has been added you will be able to reverse any of your strings:

ActionScript Code:
  1. var myText = "Hello Ultrashock";
  2. trace(myText); // output: Hello Ultrashock
  3.  
  4. myText = myText.reverse();
  5. trace(myText);// output: kcohsartlU olleH
  6.  
Maybe you would like to be able to shuffle any of your arrays? Easy enough, you add your function to the Array prototype object like this:

ActionScript Code:
  1. Array.prototype.shuffle = function() {
  2.     var a = [].concat(this);
  3.     var i = a.length;
  4.     var n;
  5.     while (i--) {
  6.         n = Math.floor(Math.random() * a.length);
  7.         this[i] = a.splice(n, 1);
  8.     }      
  9. }
Now you can shuffle any array in your movie:

ActionScript Code:
  1. var myItems = ["apple", "banana", "cherry", "doughnut"];
  2. trace( myItems ); // output: apple,banana,cherry,doughnut
  3.  
  4. myItems.shuffle();
  5. trace( myItems ); // output: doughnut,banana,apple,cherry
  6.  
You can add prototype functions to virtually any core class in Flash although it is better to create/use classes if you are able to.