Compare apply front-end interview with the classic problem of the call

  Speaking before apply and call, we need to know in the js, what this points to yes.

  We can refer to Ruan Yifeng teacher wrote on the principles of JavaScript in this article explain: http://www.ruanyifeng.com/blog/2018/06/javascript-this.html

  About the use of call and apply, simply summarized in one sentence is changed to an object in this, the role of these two methods are the same, the only difference is the incoming parameters, let's look at these two specific usage method:

. 1  / *   Apply   * / 
2  function .apply (obj, argsArray);         // passed parameter is an array 
. 3  
. 4  / *   Call * / 
. 5  function .call (obj, arg1, arg2, ..);       // the number of passed parameters are determined 
. 6  
. 7  
. 8  / * distinction apply and call parameter passing mode * / 
. 9  function the Add (C, D) {
 10      return  the this II.A + the this .B + C + D;
 . 11  }
 12 is  
13 is  var S = {A:. 1, B: 2 };
 14 console.log(add.call(s, 3, 4));       // 1+2+3+4 = 10
15 console.log(add.apply(s, [5, 6]));  // 1+2+5+6 = 14

  The first parameter is the new object we want to this point, and the second parameter is a parameter we can pass into the method to be called. We can see that, when the number of parameters is determined, we can call a method to change the call to this point, when the number of parameters are undefined, we can use these parameters inside the package into an array, by passing arrays call to apply this method to change the point of. Note that, when an incoming apply method parameter is not an array, the system will automatically error, throw a TypeError.

  The following look at the usage of call and apply:

 1 window.number = 'one';
 2 document.number = 'two';
 3 
 4 var s1 = {number: 'three' };
 5 function changeColor(){
 6     console.log(this.number);
 7 }
 8 
 9 changeColor.apply();         //one
10 changeColor.apply(window);   //one
11 changeColor.apply(document); //two
12 changeColor.apply(this);     //one
13 changeColor.apply(s1);       //three

 

 1 window.color = 'red';
 2 document.color = 'yellow';
 3 
 4 var s1 = {color: 'blue' };
 5 
 6 function changeColor() {
 7     console.log(this.color);
 8 }
 9 
10 changeColor.call();                   //red
11 changeColor.call(window);             //red
12 changeColor.call(document);           //yellow
13 changeColor.call(this);               //red
14 changeColor.call(s1);                 //blue

  This is an example I read, I think can help us quickly understand and apply call this change point is how to change.

  

Guess you like

Origin www.cnblogs.com/hmchen/p/11311420.html