当前位置: 移动技术网 > IT编程>开发语言>JavaScript > TypeScript之调用栈的实现

TypeScript之调用栈的实现

2020年03月09日  | 移动技术网IT编程  | 我要评论

本文介绍了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)}`);
  }
}

开始测试:

结果:

所以,尽量给function的参数取一些好的名字.

另外一点 , 不会出现function()这样的打印 , 出现没有参数的function , 我会将方法体内容也打印出来

如果需要把每一个function的方法体的内容打印出来callstacktool.printcallstack(2,false), 将第二个参数设置未false

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网