3. Function. Prototype But it does take some work to figure them out.

Summarize in simple words

Each of these functions can modify the context in which the function is executed, that is, to which this is pointed.

  • call( thisArg, arg1, ... , argN )
  • apply( thisArg, [argArray]
  • bind( thisArg, arg1, ... , argN )

As you can see above, the second argument to call is a list of arguments, and the second argument to apply is an array. And both Call and apply are executed immediately.

The second argument to bind is also an argument list, but it returns a function that needs to be called before it is executed, so it is passive.

Call () and the apply ()

These two functions are the same, just written differently. Call can be an argument list, and apply can be an array or an array of classes (such as Arguments).

Here’s an example:

function func(avg1, avg2) {
  console.log(avg1, avg2);
}

function apply_func() {
  return func.apply(this.arguments);
}
apply_func(1.2); / / 1. 2

function call_func() {
  return func.call(this. arguments); } call_func(3.4); / / 3 4
Copy the code

You can use both of these to implement inheritance or other techniques, depending on what you’re used to. Here’s an example of inheritance:

function Parent (name) {
    this.name = name;
}

function Child (name) {
    Parent.call(this, name);
}
Copy the code

bind()

This bind() is used more often than the previous two, and many implementations have bind.

If bind is called, bind must be called once. If bind is called, bind is called once.

Here’s a common example:

class Person {
  constructor(name) {
    this.name = name;
  }
  sayName() {
    console.log('sayName'.this.name);
  }
  sayNameDelay() {
    setTimeout(function () {
      console.log('sayNameDelay'.this.name)
    }, 1000); }}let p = new Person('Zeekg');
p.sayName(); // sayName Zeekg
p.sayNameDelay(); // sayNameDelay
Copy the code

You can see that the name in setTimeout output is undefined. Bind () is used here:

class Person {
  constructor(name) {
    this.name = name;
  }
  sayName() {
    console.log('sayName'.this.name);
  }
  sayNameDelay() {
    setTimeout(function () {
      console.log('sayNameDelay'.this.name)
    }.bind(this), 1000); // Add the code here}}let p = new Person('Zeekg');
p.sayName(); // sayName, Zeekg
p.sayNameDelay(); // sayNameDelay Zeekg
Copy the code

You can also use the setTimeout(()=> {},1000} arrow function.

Write in the last

This article is mostly a summary and does not explain much about how to use these functions.

It’s not hard, but it takes a while to figure it out.

Links:

  • Function.prototype.call() MDN

  • Function.prototype.apply() MDN

  • Function.prototype.bind() MDN

Feel free to point out any inaccuracies in the comments section