1. JS changes apply (a), bind (b), call (c) when changing the function execution context

Concise

  The three have in common:

    (1): All three are to change the context of the function execution;

    (2): The first parameter of the three is the new direction of this;

    (3): The three can pass parameters to the function through subsequent parameters;

  The difference between the three:

    The code above:

 1          let tomInfo={
 2           name:"tom",
 3           type:"cat",
 4           job:function(param1,param2,param3){
 5               console.log(this.name);
          console.log(param1);
          console.log(param2);
          console.log(param3);
6 } 7 } 8 let jerryInfo={ 9 name:"jerry", 10 type:"mouse", 11 job:function(){ 12 console.log(this.name); 13 }, 14 } 15 tomInfo.job();//job 16 tomInfo.job.apply(jerryInfo,[1,2,3],99); //jerry 1 2 3; 17 tomInfo.job.bind(jerryInfo,1,2,3)();//jerry 1 2 3; 18 tomInfo.job.call(jerryInfo,1,2,3);//
jerry 1 2 3;

    From the above code, the following three points can be summarized:

      (1): apply will execute the function that calls apply, and this points to the first parameter, the second parameter is an array, and there is no output from the third parameter.Apply only accepts two parameters, but it needs to be based on the array when receiving Get the index in turn;

      (2): bind will not execute the function that calls bind, it will return the function that calls bind, and point this to the first parameter, which can be followed by n parameters.When receiving, go to get it in turn. Bind () followed by a pair of () can be seen that the return value of bind is a function;

      (3): call will point to the function that calls the call, and this points to the first parameter; follow-up can pass n parameters, when receiving, go to get in turn;

   The above are the common points and differences of apply bind call (a, b, c);

The next article manually implements a bind function;

 

Guess you like

Origin www.cnblogs.com/hylCodeHouse/p/12702564.html