– Call, apply, and bind are all methods that change the direction of this

Method definition

  • Apply: call A method of an object and replace the current object with another object, e.g. B.ply (A, arguments)
  • Call: Calls a method on an object that replaces the current object with another. For example: the biggest all (A, the arguments); That is, the method that object A calls object B

The above definition is confusing at first glance, but when you reread it while writing the example, you will feel a sense of clearing the cloud.

Similarities between Call & apply:

  • Method meaning is the same, that is, method function is the same;
  • The first parameter does the same thing;

The difference between Call and apply: They pass different lists

  • Call can pass in multiple arguments;
  • Apply can only pass in two arguments, so its second argument is usually passed in as an array

Details in call

  1. Nonstrict mode

If no argument is passed, or if the first argument is null or undefined, this points to window

 let fn = function(a,b){
        console.log(this,a,b);
    }
    let obj = {name:"obj"};
    fn.call(obj,1.2);    // this:obj a:1 b:2
    fn.call(1.2);        // this:1 a:2 b:undefined
    fn.call();           // this:window a:undefined b:undefined
    fn.call(null);       // this=window a=undefined b=undefined
    fn.call(undefined);  // this=window a=undefined b=undefined
Copy the code
  1. Strict mode

This points to whoever the first argument points to, including null&undefined. If this is not passed, this is undefined

"use strict"
    let fn = function(a,b){
        console.log(this,a,b);
    }
    let obj = {name:"obj"};
    fn.call(obj,1.2);   // this:obj a:1 b:2
    fn.call(1.2);       // this:1 a:2 b=undefined
    fn.call();          // this:undefined a:undefined b:undefined
    fn.call(null);      // this:null a:undefined b:undefined
    fn.call(undefined); // this:undefined a:undefined b:undefined
Copy the code

apply

Apply: basically the same as call. The only difference is that the parameter is passed

Apply passes the parameters that need to be passed to fn in an array (or array of classes). Although it is written in an array, it is equivalent to passing the parameters to FN one by one

fn.call(obj, 1.2)
fn.apply(obj, [1.2])
Copy the code

bind

Bind: The syntax of call is the same as that of call. The difference is that bind is not compatible with IE6 to IE8

fn.call(obj, 1.2); // Change this in fn and execute fn immediately
fn.bind(obj, 1.2); // Change this in fn, fn does not execute
Copy the code

This is changed to obj, but is executed immediately upon binding, and undefined is returned by fn when the click event is triggered

document.onclick = fn.call(obj);
Copy the code

Bind will preprocess fn's this to obj, which will not be executed until it is clicked

document.onclick = fn.bind(obj);
Copy the code