ActionScript Custom Class With Return Type?
i just know this is a dumb question, so excuse me in advance.
i want to essentially classify a simple function in it's own .as file. the function compares integers. but i don't know how to call the class and receive 开发者_JAVA百科a boolean return.
here's my class
package
{
public class CompareInts
{
public function CompareInts(small:int, big:int)
{
compare(small, big);
}
private function compare(small:int, big:int):Boolean
{
if (small < big)
return true;
else
return false;
}
}
}
so now i'd like to write something like this:
if (CompareInts(1, 5) == true). or output 'true' by writing trace(CompareInts(1, 5));
You have 2 options:
1) Make your compare function public and static.
static public function compare(small:int,big:int):Boolean {
{
if (small < big)
return true;
else
return false;
}
}
And call it:
CompareInts.compare(1,5);
2) You don't actually need a class. You can just use a function. As long as there's only one public definition per AS file, you'll be fine (by that I mean that at the "top" level you can have a public class, an interface, a public function, a public var or a public namespace. It won't work if you try to have more than one.
package {
public function compare(small:int,big:int):Boolean {
{
if (small < big)
return true;
else
return false;
}
}
Or, you could inline this into a single line and ditch the class / function entirely (parens are not neccesary, I just added them for clarity):
var compare:Boolean = (small < big);
You are creating a
Class
and thenfunction
that are members of thatClass
so for calling them you have to instanciate theClass
and then call the function of the instance created.Also
CompareInts
is the constructor of the class it can't return anything
the working code corresponding to your class will be:
package {
public class CompareInts {
public function CompareInts(){}
public function compare(small:int, big:int):Boolean {
if (small < big)
return true;
else
return false;
}
}
}
new CompareInts().compare(1, 2);
But this a litle bit overkill so what you can do is create a static function into your class and then call it directly without the needed to instanciate the class.
package {
public class Compare {
public static function compareInts(small:int, big:int):Boolean {
if (small < big)
return true;
else
return false;
}
}
}
Compare.compareInts(1, 2)
If you don't want to group more functions into a Class you can always declare a single function into a Package:
package {
public function compareInts(small:int, big:int):Boolean {
if (small < big)
return true;
else
return false;
}
}
An AS3 constructor can never have a return value. If you want to keep this method in a class, then have the constructor just call an init() function and have init() return values.
Hope that helps clear up the "why?" that might be swirling in your head.
精彩评论