
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Completing the Box Class
|
119
Using this in Constructor Functions
Within the body of a constructor function, the this keyword refers to the newly cre-
ated instance. We use
this in a constructor function exactly as we use it from within
instance methods. For example, the following code uses
this to resolve a parameter/
property name conflict:
public function Box (width:Number, height:Number) {
// Sets width property (this.width) to value of width parameter (width).
this.width = width;
// Sets height property (this.height) to value
// of height parameter (height).
this.height = height;
}
For details on using this, see the earlier discussion under “Referring to the Current
Object with the Keyword
this.”
Constructor Functions Versus Default Property Values
Earlier in this chapter we learned that an instance property can be assigned a default
value provided the value is a compile-time constant expression, such as 10 or “hello
world”. For example:
private var x:Number = 10;
private var msg:String = "hello world";
While it’s legal to initialize an instance property by assigning it a default value, it’s a
best practice to perform all instance property initialization in a constructor function.
Constructor functions are not limited by the compile-time constant rule, so they can
safely calculate property ...