The difference between call, apply and bind

1. What are the definitions of call, apply and bind? (What are they?)

The call() method calls a function with a specified this value and one or more arguments given separately.

function func(a, b, c) {
  console.log(this.name, a, b, c)
}
const obj1 = { name: 'obj1'}
func.call(obj1, 1.2.3) // obj1, 1, 2, 3
Copy the code

The apply() method calls a function with a given this value and arguments in the form of an array (or array-like object).

const obj2 = { name: 'obj2' }
func.apply(obj2, [1 ,2.3]) // obj2, 1, 2, 3
Copy the code

The bind() method creates a new function, and when bind() is called, this of the new function is specified as the first argument to bind(), while the rest of the arguments will be

As an argument to a new function for use when calling.

const obj3 = { name: 'obj3' }
const aFunc = func.bind(obj3, 1.2.3);
aFunc(); // Execute it
Copy the code

2. What are the similarities and differences between call, apply and bind?

  • Similarities: Both can change the context in which a function is executed, handing a method from one object to another

  • Difference: Call and apply are executed immediately. The object that calls call and apply must be a Function, except that they are written differently as arguments.

    Bind is not executed immediately; the return value is a function that is called and executed.

3. Classic cases

Call usage scenarios:

  1. Object inheritance
function superClass () {
  this.a = 1;
  this.print = function () {
    console.log(this.a)
  }
}

function subClass () {
  superClass.call(this);
  this.print();
}

subClass();
Copy the code
  1. Use method
Array.prototype.slice.call(document.getElementByTagName(*))
Copy the code

Apply usage scenarios

  1. Math.max
Math.max.call(null[19.1.2])
Copy the code
  1. Implement the merge of two arrays
let arr1 = [1.2.3];
let arr2 = [4 ,5.6];

Array.prototype.push.apply(arr1, arr2);
console.log(arr1)
Copy the code

Remember short stories efficiently

Cats eat fish, dogs eat meat, ultraman fights little monsters.

Tiangou wants fish

Cat eats fish. Call (dog, fish)

The dog eats the fish

The cat got clever and wanted to fight the monster

Ultraman. Beat the little Monster. Call the cat.

Cats can fight little monsters, too

Ultraman wants to integrate the catfish’s abilities, generate a master move, and then use that master move at any time

Bind (Ultraman, cat, dog, fish)

Altman is awesome.