JavaScript/typescript/回调函数

来自康健生活
Kangkk​(留言 | 贡献)2020年9月16日 (三) 03:52的版本 (→引言)

引言

类型

声明回调函数类型:

event.on('change', function() {});
type CB = () => void;
on(type: string, cb: CB);

this

老生常谈的 this 指向问题

示例

TestCallAndThis.ts
namespace naiking
{
    /**
     *author     : NaiKing
     *description: 
     */
    export class TestCallAndThis {
        /**
         * 不推荐的回调写法
         * 外部调用必须【必须】【必须】在回调参数方法后面添加.bind(this),
         * 否则可能会this异常
         */
        public static callBackTest(arg:number,callBack:Function):void
        {
            //返回 2 x arg
            let result:number=arg*2;
            //不推荐直接调用回调方法,应使用callBack.call(caller,result);
            callBack(result);
        }
        /**
         * 推荐的回调写法
         * @param arg 参数
         * @param caller 调用域 
         * @param method 指定的回调方法(兼容.bind(this) 也可以不加.bind(this) )
         */
        public static callMethod(arg:number,caller:any,method:Function):void
        {
            //返回 2 x arg
            let result:number=arg*2;
            //推荐的做法 .call(caller,result);
            method.call(caller,result);
           
        }
    }
}

(来源摘自互联网示例,作者 https://www.cnblogs.com/naiking/p/9836289.html)

测试.ts
namespage naiking
{
   export class Luna
   {    //注意观察,this异常的时候的isLoading的值是undefind
      private isLoading:boolean = false;
      private getResult(rst:number):void
      {
          console.log("get rusult:"+rst+this.isLoading);
        
      }
      constructor()
      {
          //不推荐的回调写法, 遗漏了bind(this)
          logic.TestCallAndThis.callBackTest(1,this.getResult);
          //不推荐的回调写法, 使用了bind(this)( √ )
          logic.TestCallAndThis.callBackTest(1,this.getResult.bind(this));
        
          //提倡的回调写法 ,有无bind(this)都可以
          logic.TestCallAndThis.callMethod(1,this,this.getResult);
          logic.TestCallAndThis.callMethod(1,this,this.getResult.bind(this));
      }   }}

(来源摘自互联网示例,作者 https://www.cnblogs.com/naiking/p/9836289.html)