TypeScript之調用棧

class CallStackTool{
    private static index:number = 0;
    public static printCallStack (count:number , simple: boolean = true):void {
        let caller:Function = arguments.callee.caller;
        let i:number = 0;
        count = count || 10;
        CallStackTool.index ++;
        if( CallStackTool.index > 500 )  CallStackTool.index = 1;
        console.log(`***-----------------${CallStackTool.index}Start-----------------------  **`);
        while (caller && i < count) {
            console.log(`${(i+1)}: \n ${CallStackTool.getFunctionName(caller,simple)}`);
            caller = caller.caller;
            i++;
        }
        console.log(`***-----------------${CallStackTool.index}End-----------------------  **`);
    }

    private static getFunctionName(func:any,simple: boolean):string {
        if( simple ){
            let name:any;
            if ( typeof func == 'function' ) {
                name =  ('' + func).match(/function\s*\((\s*\$*\S+\s*,)*(\s*\$*\S+\s*)?\)/g);
                let $result: string = name && name[0];
                if( $result != `function ()` ){
                    return $result;
                }
            }
        }
        return func.toString();
    }
}

測試代碼:

class Test2CallStack{

    public add( i:number, b:number ):number{
        CallStackTool.printCallStack(2,true);
        return i +b;
    }

    public a( c:number, q:number ): number{
        return this.add(c,q);
    }

    public print() : void{
        console.log(`${this.a(1,1)}`);
    }
}

開始測試:
TypeScript之調用棧

結果:
TypeScript之調用棧

所以,儘量給function的參數取一些好的名字.
另外一點 , 不會出現function()這樣的打印 , 出現沒有參數的function , 我會將方法體內容也打印出來

如果需要把每一個function的方法體的內容打印出來CallStackTool.printCallStack(2,false), 將第二個參數設置未false

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章