AS3 Instances Functions

The educational technology and digital learning wiki
(Redirected from Built In Functions)
Jump to navigation Jump to search


This article is part of the ActionScript 3 tutorials.

Before we go into a lot of technical detail I'm going to give you a scenario.

You are a foreman in a production line in a tomato tinning factory. You have four workers under you, each having a specialised purpose.

Fred is the tomato boiler, he collects the tomatoes and cooks them in a big vat before they get funelled to Mary, who controls the machine that fills the empty tins, then Sahib is in charge of the tin sealing machine and finally Ken is the truck driver who delivers the whole lot to the warehouse for distribution.

In this scenario, each worker has a specialised function, Fred can only boil tomatoes, Mary can only fill tins, Sahib can only seal tins and Ken exclusively drives trucks. Don't ask these employees to do anything else, because they'll look at you blankly, they do the job they're trained to do...

How does this relate to Actionscript functions? Fred, Mary, Sahib and Ken, are all people with very limited skill sets, but they all perform their jobs perfectly, just like a well coded function in Actionscript 3.0.

When you create a function, you would have decided what that function will do before hand, for example, Ken might look something like this as an Actionscript function:

   function Ken() {
       deliver tins to warehouse... 
   }

of course, Ken is not a very descriptive name for this function. We want to know what the function does just by looking at it.

So, let's call it...

    function deliverTinsToWarehouse() { 
       put some code in here that "delivers our tins"... 
    }

Now, if we want to use our function we "call" it. Just like a foreman might call one if his staff.

package {
    import flash.display.Sprite;
        
    public class TomatoFactory extends Sprite {
        
    public function TomatoFactory() {
         // call 'Ken'
          deliverTinsToWarehouse();
      }
        
    private function deliverTinsToWarehouse(){
         trace("Ken delivers the tins to the warehouse.");
       }
    }
}

Notice that line 4 function TomatoFactory() is also a function. This is called a "constructor", but this is an area covered elsewhere in this tutorial (>> add link <<).

Try running this code.

Task

Create functions that performs the actions of the other three factory workers, eg. create a boilTomatoes() function... you come up with the rest!

Implications

Consider how functions help with coding, especially when you need to perform the same task in several different places in your code. Instead of copying pasting the code over and over again, you just create a function and use that as a placeholder. Every time you need to perform that task, you 'call' that function.