First of all, when we execute the function, we directly put parentheses after the function, such as _f1(), _. However, in fact, our function call execution method can also use all, apply dynamic call, and this call method can let us have a clearer understanding of the pointing of _this_ in the function.

  • this

We want the function to get a reference to the object, but we don’t want to do that by adding extra variables and setting parameters. Js does this with an extra set of this.

Let Person = {name: 'DSPLK ', sayHi(){console.log(' my name')+ this.name}} persopn.sayhi () // equal to person.sayhi (Person)Copy the code

This way, every function can use this to get a reference to an unknown object.

  • Call way

Call, apply, and bind are all explicit calls to this as follows:

  1.call( )

Fn. call(this,x1,x2) // The first argument to call is the value to bind to this, followed by a list of arguments. // When the first parameter is null, undefined, the default point is window.Copy the code

Use our usual call method to understand:

obj1.fn() 
obj1.fn.call(obj1);

fn1()
fn1.call(null)

f1(f2)
f1.call(null,f2)
Copy the code

  2.apply( )

Var arr = [1,2,3,89,46] var Max = math.max. Apply (null,arrCopy the code

 3.bind( )

Use bind() to keep this unchanged

var obj = { name: 'Dot' } function printName() { console.log(this.name) } var dot = printName.bind(obj) console.log(dot) // function () { ... } dot() // equivalent to printname.call (obj)Copy the code

Bind () can also bind other parameters

Let the f3 = f1. Bind ({name: 'DSPLK},' h1) f3 () / / equivalent to the f1. Call ({name: 'DSPLK},' h1)Copy the code

  • conclusion

Bind returns the corresponding function for later call; Apply, call is called immediately.

In addition, call and Apply are disabled under ES6’s arrow functions