AS3 calling a global function with out 'new' or having a static method
I'm creating a utility function for debugging/logs, which I access by importing the class and calling
new Log(params);
Alternatively I change the function to a static, and rename it to It
,
then I can call it by Log.It(params)
I'm wondering if it possible to set it up so I can simply call Log(params)
similar to the trace
command?
function:
package
{
public class Log
{
/** Gets the name of the function which is calling */
public function Log(prefix:String = "", suffix:String = "", params:* = null):void
{
var error:Error = new Error();
var stackTrace:String = error.getStackTrace(); // entire stack trace
var startIndex:int = stackTrace.indexOf("at ", stackTrace.indexOf("at ") + 1); //start of second line
var endIndex:int = stackTrace.indexOf("()", startIndex); // end of function name
var l开发者_开发知识库astLine:String = stackTrace.substring(startIndex + 3, endIndex);
var functionSeperatorIndex:int = lastLine.indexOf('/');
var ClassSeperatorIndex:int = lastLine.indexOf(':');
var objectName:String = lastLine.substring(ClassSeperatorIndex+2, functionSeperatorIndex);
var functionName:String = lastLine.substring(functionSeperatorIndex + 1, lastLine.length);
//TODO: Loop through params
trace(prefix +" " + "[" + objectName + "]" + " > " + functionName + " " + suffix);
//TODO: Log to Array
//TODO: Dispatch Event
}
}
}
You could create package level methods(I don't know if that's the correct term), here's an example:
concat.as:
package com.example.utils
{
public function concat(string1:String, string2:String):String
{
return string1.concat(string2);
}// end function
}// end package
Main.as(document class):
package
{
import com.example.utils.*;
import flash.display.Sprite;
import flash.events.Event;
public class Main extends Sprite
{
public function Main():void
{
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}// end function
private function init(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
var string1:String = "Hello";
var string2:String = "World";
var string3:String = concat(string1, string2);
trace(string3); // output: HelloWorld
}// end function
}// end class
}// end package
精彩评论