基本语法
- 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