基本语法
- 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
本文深入解析JavaScript中的bind方法,展示了如何使用bind改变函数内部的this指向,并通过具体实例说明其工作原理。bind方法允许开发者为函数预设参数,同时修改函数执行时的上下文环境。
1816

被折叠的 条评论
为什么被折叠?



