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

Chapter 3. Instance Methods Revisited

In Chapter 1, we learned how to create instance methods. In this chapter, we'll expand that basic knowledge by studying the following additional instance-method topics:

  • Omitting the this keyword

  • Bound methods

  • State-retrieval and state-modification methods

  • Get and set methods

  • Extra arguments

Along the way, we'll continue developing the virtual zoo program that we started in Chapter 1. But before we begin, take a minute to reacquaint yourself with the virtual zoo program. Example 1 shows the code as we last saw it.

Example 1. Zoo program

// VirtualPet class
package zoo {
  internal class VirtualPet {
    internal var petName;
    private var currentCalories = 1000;
    private var creationTime;

    public function VirtualPet (name) {
      this.creationTime = new Date();
      this.petName = name;
    }

    public function eat (numberOfCalories) {
      this.currentCalories += numberOfCalories;
    }

    public function getAge () {
      var currentTime = new Date();
      var age = currentTime.time - this.creationTime.time;
      return age;
    }
  }
}

// VirtualZoo class
package zoo {
  public class VirtualZoo {
    private var pet;

    public function VirtualZoo () {
      this.pet = new VirtualPet("Stan");
    }
  }
}

Omitting the this Keyword

In Chapter 1, we learned that the this keyword is used to refer to the current object within constructor methods and instance methods. For example, in the following code, the expression this.petName = name tells ActionScript to set the value of the instance variable petName on the object currently being created: ...

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