共同之处:这三个都是 Function类 提供的方法,作用和用法都跟 Java 反射里面的 invoke 差不多,都是拿到一个方法之后对它进行调用。
一. 先来看看 call,弄懂之后,其它两个触类旁通
//1.call 可以调用函数
function fun1() {
console.log('hello, world.')
}
fun1.call();
//2.call 可以改变this的指向
function fun2(){
console.log(this.name);
}
let obj = {
name: 'steward'
}
fun2.call(obj);
//这里啥都不传,在浏览器中this是默认指向window的,
//this.name就是window.name,输出是一个空串;
//而在node的环境中,this是默认指向undefined,
//所以undefined.name会报错,因为不能从undefined中读取任何属性。
//3.call 的第一个参数是this指向,后面还有一个可变参数,具体多少个由函数本身决定
function fun3(food1, food2) {
console.log(`I like to eat ${food1} and ${food2}.`);
}
fun3.call(null, 'meat', 'fruit');
二. call 的使用就是以上三个,apply 的使用跟 call 完全一样,只是在传参的时候不再是一个可变参数,而是一个数组。
fun3.call(null, 'meat', 'fruit');//可变参数传递,有几个写几个
fun3.apply(null, ['meat', 'fruit'])//数组传递,参数都写在数组里
三. bind 的使用跟 call 是一模一样,传参方式也是可变参数。唯一的区别是bind不会调用函数,而是返回一个新的函数。
let newFun3 = fun3.bind(null, 'meat', 'fruit');
newFun3();//调用
//等价写法:fun3.bind(null, 'meat', 'fruit')() === fun3.call(null, 'meat', 'fruit')