The purpose of these three functions is to change the this reference of the function at runtime
let obj = {name:'tony'};
function Child(name) {
this.name = name;
}
Child.prototype = {
constructor:Child,
showName:function(){
console.log(this.name); }}var child = new Child('Joe')
child.showName(); / / zhang SAN
/ / call, apply, use the bind
child.showName.call(obj); //tony
child.showName.apply(obj); //tony
let bind = child.showName.bind(obj);// Return a function
bind(); //tony
Copy the code
bind
The bind method changes fn’s this to the desired result and prepares the corresponding parameter values for later use. This means that bind can also change the direction of this, but unlike apply and call, it will not be used immediately
The bind method is not compatible with IE6 ~8
The difference between
Three functions do the same thing, why are there three, because there are differences
- Call, apply, bind
Call and apply execute a function after its this context has been changed, while bind returns the function after the context has been changed
- The difference between call and apply
The difference between call and apply lies in the parameters. The first parameter of call and apply is the object to change the context. Call is presented as a list of parameters starting with the second parameter
let arr1 = [1.2.19.6];
console.log(Math.max.call(null.1.2.19.6)); / / 19
console.log(Math.max.call(null, arr1)); // NaN
console.log(Math.max.apply(null, arr1)); // 19 can be passed directly in with arr1
Copy the code