call, apply, and bind are called strong bindings of this and are used to change the this pointer when a function is executed. All current uses of them are based on this point.
apply()
The apply() method receives two parameters: one is the scope in which the function is run, and the other is the parameter array. Among them, the second parameter can be an instance of Array or an arguments object.
The call() method has the same function as the apply() method. The only difference between them is the way they receive parameters. When using the call() method, the parameters passed to the function must be listed one by one.
The results returned by the call() method and the apply() method are exactly the same. As for whether to use apply() or call(), it all depends on which method of passing parameters to the function is most convenient.
Number of parameters: If the order is determined, use call. If the order is uncertain, use apply.
Consider readability: if the number of parameters is small, use call. If the number of parameters is large, integrate the parameters into an array and use apply.
bind()
The bind() method creates an instance of a function whose this value is bound to the value passed to the bind() function. This means that bind() will return a new function
window.color ='red'var o ={
color:'blue'}functionsayColor(){
alert(this.color)}var objectSayColor =sayColor.bind(o)objectSayColor()//blue
The difference between call, apply and bind
implement:
call/apply executes the function immediately after changing the this context of the function
bind returns the function after changing the context and does not execute the function
functionadd(a, b){
return a + b
}functionsub(a, b){
return a - b
}add.bind(sub,5,3)// 这时,并不会返回 8add.bind(sub,5,3)()// 调用后,返回 8
return value:
call, apply returns the execution result of fun
bind returns a copy of fun, specifies the this pointer of fun, and saves the parameters of fun.
The core concepts of call, apply and bind
From the above simple examples, we can see that call, apply, and bind are borrowing methods from other objects. Object A has a method, and object B also needs to use the same method for some reason. At this time, B can borrow it. The method of object A not only achieves the purpose, but also saves memory.