TypeScript: this bind 和 回调的正确用法
发布时间:2020-12-14 04:17:54 所属栏目:大数据 来源:网络整理
导读:TypeScript 中如果传递了 而且在回调函数中用了this 的话,就要小心了,这个this 不一定 是指向当前类对象了, 如果想确保指向的还是那个对象的话,需要在传递那个方法的时候,先调用bind(this). 或者就是在回调的时候,不要直接func(agrs) 而是改成 func.call(目
TypeScript 中如果传递了 而且在回调函数中用了this 的话,就要小心了,这个this 不一定是指向当前类对象了, 示例: TestCallAndThis.ts 提供了2种回调的写法,第二种是推荐的写法
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); } } } 调用(测试) namespage naiking { export class Luna { 运行第一种,this的指向是异常的,自然this.isLoading是undefind ? 打印的测试log: get rusult:2undefined? ? ? ? ? ? ? ? ? ? ? ? 后面的几种,都是正常的结果 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |