作用
call、apply、bind的作用都是改变函数执行时的执行环境,也就是改变函数运行时的this指向。
call,和apply,bind的相同和区别
- 三者的作用都是可以改变函数的this指向
- 三者的第一个参数都是this要指向的对象,如果为null和undefined,则默认指向window,如果是传递字符串等基础类型,this则指向Stringr等对应对象。
- apply、call绑定this后是立即执行,bind则是返回绑定this之后的函数。
- 三者都是第二个参数开始传参。apply传参数以数组形式,参数个数不确定的情况;call以参数列表形式,一般用于参数确定的情况;bind传参以列表形式,可以多次传参。
call和apply
apply、call绑定this后是立即执行,apply传参数以数组形式,call以参数列表形式;两者的一般用法
var name="react"
let a={
name:"vue",
fn:function(){
console.log(`${arguments[0]}已经学习${arguments[1]}天的${this.name}`)
}
}
let b={
name:"js"
}
let fn2=a.fn;
fn2("张狂",30);//相当于a.fn.call(window,"张狂",30)。张狂已经学习30天的react
a.fn.call(b,"小明",20);//小明已经学习20天的js
a.fn.apply(b,["花花",20])// 花花已经学习20天的js
bind
bind方法会返回的是一个修改过this的函数。bind可以多次传参,参数按传入顺序存放到arguments中。注意:this只能修改一次。
function add(){
let count=0;
for(let i=0;i<arguments.length;i++)count+=arguments[i];
return count;
}
add2=add.bind(null,1,2);
console.log(add2(3,4))//10
使用实例
数组借用Math的方法
var arr=[1,4,166,9]
console.log("math",Math.max.apply(arr,arr))//363
console.log(Math.max(...[1,363,2]))
Array.prototype.min=function(){
return Math.min.apply(this,this)//改变内部this指向,并且传参
}
console.log("min",arr.min())//1