O'Reilly logo

Essential ActionScript 3.0 by Colin Moock

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Bound Methods

In ActionScript, a method can, itself, be treated as a value. That is, a method can be assigned to a variable, passed to function or another method, or returned from a function or another method.

For example, the following code creates a new VirtualPet object, and then assigns that object's eat( ) method to the local variable consume. Notice that in the assignment statement, the method-call parentheses, ( ), are not included after the method name. As a result, the method itself—not the method's return value—is assigned to the variable consume.

package zoo {
  public class VirtualZoo {
    private var pet;

    public function VirtualZoo () {
      pet = new VirtualPet("Stan");
      // Assign the method eat() to a variable
      var consume = pet.eat;
    }
  }
}

A method assigned to a variable can be invoked via that variable using the standard parentheses operator, ( ). For example, in the following code, we invoke the method referenced by the variable consume:

package zoo {
  public class VirtualZoo {
    private var pet;

    public function VirtualZoo () {
      pet = new VirtualPet("Stan");
      // Assign a bound method to consume
      var consume = pet.eat;
      // Invoke the method referenced by consume
      consume(300);
    }
  }
}

When the preceding bolded code runs, the eat( ) method is invoked and passed the argument 300. The question is, which pet eats the food? Or, put more technically, on which object does the method execute?

When a method is assigned to a variable and then invoked through that variable, it executes on the object ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required