Publishers of technology books, eBooks, and videos for creative people

Home > Articles > Design > Adobe Creative Suite

  • Print
  • + Share This
This chapter is from the book

About Functions

If objects and classes are at the heart of ActionScript, functions must lie in the brain. Functions are the organizers of ActionScript. Functions group related ActionScript statements to perform a specific task. Often, you need to write code to do a certain thing over and over again. Functions eliminate the tedium and the duplication of code by putting it in one place where you can call on it to do its job from anywhere and at any time, as many times as you need.

As you learned earlier in this chapter, the objects Adam, Betty, and Zeke can perform certain tasks, called methods. If these objects were to put on a dinner party, they could organize themselves and do the following:

Adam.answerDoor();
Betty.serveDinner();
Zeke.chitChat();

But every Friday night when they have a dinner party, you would have to write the same three lines of code—not very efficient if these objects plan to entertain often. Instead, you can write a function that groups the code in one spot.

function dinnerParty () {
	Adam.answerDoor();
	Betty.serveDinner();
	Zeke.chitChat();
}

Now, every Friday night, you can just invoke the function by name and write the code, dinnerParty(). The three statements inside the function's curly braces will be executed. You can add a function in Normal mode by choosing Actions > User-Defined Functions > function (Esc-fn).

You will also be using anonymous functions. As their name suggests, anonymous functions are not named and look something like this:

function() {
	Adam.answerDoor();
	Betty.serveDinner();
	Zeke.chitChat();
}

Anonymous functions do not work alone and must be assigned to another object.

myButton.onPress = function() {
	Adam.answerDoor();
	Betty.serveDinner();
	Zeke.chitChat();
}

Now your three friends perform their jobs when the object called myButton is clicked.

You will learn much more about named functions and anonymous functions in the upcoming chapters, after you have a few more actions and concepts under your belt. Anonymous functions are important for handling events (Chapter 4) and for creating your own methods for objects (Chapter 11). Named functions are important for building reusable code (Chapter 11).

  • + Share This
  • 🔖 Save To Your Account