TypeScript 系列之 bind

基本语法

  • bind 函数返回由指定的 this 和 初始化参数改造的原函数的拷贝
  • func.bind(this, args[])

实例

class A{
    private z: string = "class A";
    testBind(x: any, y: any){
        console.log(`show x = ${x}, y = ${y}, z = ${this.z}`);
    };
    show(obj: any, x: any, y: any){
        obj.show(this.testBind.bind(obj, x, y));
    }
}

class B{
    private z: string = "class B";
    show(func: any){
        func();
    }
    test(){
        var a: A = new A();
        a.show(this, 3, 4);
    }
}

var b: B = new B();
b.test();

直接看代码,在A.show中通过bind创建了一个testBind的拷贝,并且改变了函数中的this
所以最后的输出:show x = 3, y = 4, z = class B

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值