入参
call
: 参数数量不固定。第一个参数指定了函数体内的this指向,从第二个参数开始往后,每个参数被依次传入函数。
apply
: 接受两个参数。第一个参数指定了函数体内的this指向。第二个参数接受一个数组 [1,2],但函数拿到的是解构后的入参 1,2 (同call效果)。
bind
: 同call。
注意: 第一个入参为null时是用来占位,不改变this指向。
区别
call
与apply
:第二个入参不同,接受参数数量不同。
bind
与call
,apply
:bind创建一个新的函数,不会直接执行,可以固定写多个传参;call
,apply
会直接执行;
demo
var person = function(one, two, ...other) {return `${this.firstName},${this.lastName},${one},${two},${other}`}var person1 = {firstName: 'A',lastName: 'B'}// 【apply】this指向: 使person方法的this指向了person1,此时可以使用person1上的方法和属性const a = person.apply(person1, ['C', 'D', 'E', 'F']); // A,B,C,D,E,F// 【call】 this指向: 同apply;const b = person.call(person1, 'C', 'D', 'E'); // A,B,C,D,E// 【bind】 this指向: 同apply;// 创造出一个新的函数bindFun1,而bindFun1其实就是绑定了person,且person的this指向了person1const bindFun1 = person.bind(person1);console.log('==========(bindFun1)========>>>', bindFun1('C', 'D')); // A,B,C,D,// 固定一个参数C,调用时传入两个参数const bindFun2 = person.bind(person1, 'C');console.log('==========(bindFun2)========>>>', bindFun2('D', 'E')); // A,B,C,D,E// apply使用场景:当一个函数的入参是非数组,而你的数据是数组时可以使用Math.max(1, 2, 3) // 3Math.max([1, 2, 3]) // 报 错Math.max.apply(null, [1 , 2, 3]) // 3