Usage of call, apply and bind

Posted Jun 15, 20202 min read

When changing the direction of this, these three methods are often confused. The following will sort out the usage and difference of the three in detail.

Call() method

- The call() method can have countless parameters

- The first parameter is to change the object pointed to by this

- The following parameters are directly passed to the function itself

- After use, it will be automatically executed

vara={

name:'Zhang San'

}



varb={

name:'Li Si',

sayName:function(a,b,c){

console.log(this.name, a+b+c)

}

}



b.sayName.call(a, 1, 2, 3)

//output --> Zhang San 6

Apply() method

-Apply() method can only consist of two parameters

- The first parameter is to change the object pointed to by this

- The second parameter must be an array

- It will be executed automatically after use

vara={

name:'Zhang San'

}



varb={

name:'Li Si',

sayName:function(a,b,c){

console.log(this.name, a+b+c)

}

}



vararr=[1,2,3]



b.sayName.apply(a,arr)

//output --> Zhang San 6

The bind() method

- bind() method can have countless parameters

- The first parameter is to change the object pointed to by this

- The following parameters are directly passed to the function itself

- It will not be executed automatically after use and will return a new function

vara={

name:'Zhang San'

}



varb={

name:'Li Si',

sayName:function(a,b,c){

console.log(this.name, a+b+c)

}

}



varc=b.sayName.bind(a,1,2,3)

//The new function needs to be called manually to be executed

c()

//output --> Zhang San 6

What the three methods have in common

- The first parameter is to change the object pointed to by this

- In non-strict mode, if the first parameter is null/undefined, this defaults to window

- In strict mode, if the first parameter is null/undefined, this defaults to undefined

The difference between the three methods

Here is a chart to show

Method name Number of possible parameters Whether to execute automatically
call countless yes
appy Two, the second must be an array Yes
bind countless No, will return a new function