call() apply() bind()都是用来冲定义this对象的,只是参数和返回方式不同。
可以看下面的例子:
var obj={
name:'dlj',
age:20,
func:function(){
console.log(`${this.name} age is ${this.age}`);
},
func1:function(age ,name){
console.log(`name is ${this.name},age is ${age},second name is ${name}`)
}
}
var t={
name:"dlj0",
age:30,
}
obj.func();//输出 dlj age is 20
obj.func.call(t);//输出 dlj0 age is 30
obj.func.apply(t);//输出 dlj0 age is 30
obj.func.bind(t)();//输出 dlj0 age is 30
obj.func1(40,"dlj2");
//输出 name is dlj,age is 40,second name is dlj2
obj.func1.call(t,40,"dlj2");
//输出 name is dlj0,age is 40,second name is dlj2
obj.func1.apply(t,[40,"dlj2"]);
//输出 name is dlj0,age is 40,second name is dlj2
obj.func1.bind(t,40,"dlj2")();
//输出 name is dlj0,age is 40,second name is dlj2
当然 call() apply() bind()三者的参数可以是任何类型,函数 object等均可。