< Day Day Up > |
One last addition in ActionScript 2.0 as it applies to properties is the addition of the keyword static . A static property is a property of the class, as opposed to a property of an instance of a class. This allows for an easy, non-redundant way for each member of a class to share a particular piece of data. Built-In Objects with Static PropertiesWhile the term static property may seem like a new concept, the reality is that we have dealt with static properties in Flash development for years . The properties of the Math class are all static properties. They are never invoked against an instance of the Math class; instead, they are invoked against the class itself. Consider the syntax we use to refer to the value PI : var ecircumference = Math.PI * diameter; Notice how PI is referred to as a property of the Math class, not as a property of an instance of the Math class.
Adding Static Properties to Custom ClassesIn addition to built-in objects having static properties, it is also possible for us to add static properties to our own classes. To declare a property as static, we use the static keyword before the var declaration, but after the public or private declaration, if it exists. Listing 3.5 shows the declaration of a static property in an Employee class. Listing 3.5. A Newly Defined Employee Class Is Using a Static Property Describing the Company for which the Employee Is Workingclass Employee { private var firstName:String; private var lastName:String; private static var company:String = "Tapper.net Consulting"; function getCompany():String{ return Employee.company; } function getFirstName():String{ return this.firstName; } } In addition to instance properties firstname and lastname (an instance property is any property attached to an instance of a class), a static property is defined to hold the company name . This is a good fit for a static property, as any employee in the system is, by definition, an employee of this company. It's important to notice the difference between the getter methods for the instance property ( getFirstName ) and the static property ( getCompany ). The getFirstName() method returns this.firstName . This works because the keyword this refers to an instance of the class, so when getFirstName () is invoked, it returns the firstName property of that instance. The getCompany() method returns Employee.company because company is a static property. Therefore, it belongs to the class Employee , rather than to any instance of the class. If this method was mistakenly coded as shown in the following code, the compile-time error shown in Figure 3.7 would be thrown. function getCompany():String{ return this.company; } Figure 3.7. A compile-time error is thrown if a static property is referred to as an instance property.
|
< Day Day Up > |