First, to review the past:

1. Call, apply, bind we can modify this to be the object we specify. We can explicitly bind this with the first argument to these methods

2. Usage:

func.call(thisArg,arg1,arg2,….)

func.apply(thisArg,[arg1,arg2,….] )

func.bind(thisArg[, arg1[, arg2[, …]]])

The difference between Call and apply is that the Call method accepts a list of parameters, while the apply method accepts an array of parameters.

The bind method, on the other hand, sets this to the given value, returns a new function, and calls the new function with the given argument list as the first items of the original function’s argument sequence.

What does Bind do

Create a new function

The new function’s this points to the first argument of bind()

The remaining arguments to bind are used as arguments to the new function

Based on using

function foo(name){
    return `${name}`+this.age
}
let Foos = foo.bind({age:18})
Foos('tcc') //tcc18

Copy the code

Write a bind

ES5 way

Function.prototype.bind = Function.prototype.bind || function() {
var self = this
var rest1 = Array.prototype.slice.call(arguments)
var context = rest1.shift()
return function() {
var rest2 = Array.prototype.slice.call(arguments)
return self.apply(context, rest1.concat(rest2))
	}
}

Copy the code

ES6 way

Function.prototype.bind = Function.prototype.bind || function(... rest1){ const self = this const thisArg = rest1.shift() return function(... rest2){ return self.apply(thisArg,[...rest1,...rest2]) } }Copy the code

Note: If you pass null or undefined as a binding object for this to call, apply, or bind, these values will be ignored during the call, and the default binding rules will apply.

Var a = 'hello' function foo() {console.log(this.a)} foo.call(null)Copy the code