Reputation: 1758
What are the main differences (advantages/disadvantages) of declaring functions inside the default constructor function of a new class and functions declared outside the default constructor function? Is the access to access modifiers the only reason to declare functions outside default constructor functions?
Thank you.
Upvotes: 1
Views: 668
Reputation: 22604
If you mean this:
public class MyClass {
public function MyClass() {
function myFunction() : void {
}
}
}
then the main difference is not only visibility, but scope: myFunction()
is declared as a temporary function, which can only be called from within the same method. After execution of the constructor is done, the function is discarded and garbage collected, as would any temp variable. You can easily verify this: Simply add a "regular" member function and try to call myFunction()
from there - compilation will fail. So, of course, will trying to access the function from another class.
If you were referring to declaring the function as a variable, and initializing it from within the constructor, the main difference is type safety.
Consider this standard declaration:
public class MyClass {
public function myFunction ( param1:String ) : String {
// doSomething
return myString;
}
public function MyClass() {
}
}
We've declared a member function with a strictly typed parameter and a strictly typed return type. If we try to access this function in a way that does not comply with the declaration, the compiler will throw an error, and compilation will fail, just as one would expect.
Now the same declaration from within the constructor:
public class MyClass {
public var myFunction : Function;
public function MyClass() {
myFunction = function ( param1:String ) : String {
// doSomething
return myString;
}
}
}
We've declared a strictly typed member variable of type Function that is initialized to do the same thing as the member function above. But its strictly typed parameter and return type are evaluated by the compiler only within the scope of the declaration - if, for example, you try to access the function specifying too many parameters:
myClassInstance.myFunction ("whatever", "and", "some", "more");
the compiler won't complain, because both the parameter and return type are now only checked at runtime, instead of at compile time (there would still be an error, of course). So the major disadvantage of this approach is the lack of compile time type checking - errors will occur at runtime and will thus be harder to debug.
One advantage of this approach is that we could exchange this function at any time:
myClassInstance.myFunction = function ( i:int ) : void { trace (i); };
This is perfectly legal and will obviously change the object's behavior significantly. If we would do the same in the member function example, the compiler would also throw an error.
Upvotes: 4