Since actionscript 3.0 is based on ECMAscript it shares some similarities with javascript. One such similarity that I have been playing around with is creating Objects from functions.
In javascript to create an object,
var student = new Student( 33 );
document.write( student.age );
function Student( age ){
this.age = age;
}
In actionscript 3.0 Objects are usually created through class, but Objects may be created, like in javascript, through constructer functions.
package{
import flash.display.Sprite;
public class Main extends Sprite{
public function Main(){
var student = new Student( 33 );
trace( student.age );
}
}
}
function Student( age ) {
this.age = age;
}
However I get a compile error with the above code
Loading configuration file C:\Program Files\Adobe\Flex Builder 3\sdks\3.1.0\frameworks\flex-config.xml C:\Documents and Settings\mallen\Desktop\as3\Main.as(5): col: 23 Error: Incorrect number of arguments. Expected 0 var student = new Student( 33 ); ^
I was wondering why this is? To make things even weirder, the following code does work
package{
import flash.display.Sprite;
public class Main extends Sprite{
public function Main(){
Student( 33 );
var student = new Student();
trace(student.age);
/* When I add the two lines below, the code wont compile? */
//var student2 = new Student( 33 );
//trace(student2.age);
}
}
}
function Student( age ){
this.age = age;
trace(age);
}
The output for this code is
33 undefined undefined