A constructor function is a special type of method belonging to a class that you use to initialize the class. The constructor function is called whenever you create an instance of the class using the new
operator, as discussed in Explicitly and implicitly importing classes.
The constructor function always has the same name as the class itself. You can also pass parameters to the constructor.
classclassName
{ functionclassName
(arg1, arg2, ..., argn) { //initialize class here } }
For example, the following code is a constructor function for the Plant class:
// Constructor function Plant (leafType:String, bloomSeason:String) { setLeafType(leafType); setBloomSeason(bloomSeason); }
The Plant
constructor function takes two parameters of type String: leafType
and bloomSeason
. You pass values for these parameters when you create an instance using the new
operator. The following code creates an instance of the Plant class named forsythia
, whose leafType
and bloomSeason
parameters are set to Deciduous
and Spring
, respectively:
var forsythia:Plant = new Plant("Deciduous", "Spring");