Call method

The Fall and Apply methods are methods of functions and can be called with functions or methodsCopy the code

(1) You can change the direction of this

function fn(){
        // This points to window
        console.log(this);
      }
fn()
Copy the code

No doubt this must point to the window, output view

Next, call the call method

<body>
    <div class="app">I am a div</div>
    <script>
      function fn(){
        // This points to window
        console.log(this);
      }
      let div = document.querySelector('div');
 
      fn.call(div)
    </script>
</body>
Copy the code

You can see that this refers to the div element ==> Call can change the reference of this or link two unrelated elements

(2) Call also allows one element to call another element’s methods

Note: the rabbit is calling the dog’s method. In the call method, a and b are the values that need to be passed

Let rabbit = {name:' small white rabbit '} let dog = {eat(a,b){console.log(' I like to eat ',a + 'and '+ b); }} dog.eat. Call (rabbit,' turnip ',' turnip ')Copy the code

The apply method

The apply method works the same as the call method, except for the way values are passed

Mode: To pass values as arrays

Dog.eat.apply (rabbit,[' turnip ',' cabbage ']) dog.eat.apply(rabbit,[' turnip ',' cabbage '])

The bind method

The bind method also does the same thing as the call method, except that it returns the result, a function

let fun = dog.eat.call(rabbit,'carrots'.'green')
console.log(fun)
Copy the code

At this point, fun outputs the same result as calling the call method