apply and call understanding of JavaScript function (Function)

  • 2020-07-21 06:47:14
  • OfStack

JavaScript function calls are divided into four modes:

1. Method invocation pattern: that is, the object contains method attributes, Obj.methodName () or Obj[methodName]().
2. Function call mode: methodName().
3. Constructor invocation pattern: new MethodName().
4. apply and call invocation pattern: namely ObjA. apply (ObjB, args []) or ObjA. call (ObjB arg1, arg2...). .

When a function call receives this and arguments in addition to formal arguments. Where this is the function object context and arguments is the actual parameter.
apply and call do the same thing, switching the context of the function object (the reference that this points to), except that the formal arguments are different. apply is an arguments or array, and call is a comma separated number of individual form parameters.


function add(c) 
{ 
  alert(this.a+this.b+c); 
} 
var test={a:1,b:2} 
add.call(test,3);


In performing add. call (test, 3); Before add and test belong to window, at this time, this points to window. add. call (test, 3); Executes, enter add method body, this by window switch for the test, this. At this time. a = test a, this. b = test. b, c to form the value of the incoming parameters namely alert (), the result is 1 + 2 + 3 = 6. apply is also one of the functions.

Extension and inheritance through apply and call:


function Animal(name){   
   this.name = name;   
   this.showName = function(){   
     alert(this.name);   
   }   
 }   
   
 function Cat(name){  
   Animal.call(this, name); 
 }   
   
 var cat = new Cat("Black Cat");// When executed, Cat The body of the function of the this by window Switch to a Cat{} .  
// Animal The body of the function of the this.name Pass in the formal parameter is Black Cat And, ultimately, cat 
 // The answer is zero cat=Cat{name:"Black Cat",showName: function(){ alert(this.name);} .  
 cat.showName();// Execution time this by window Switch to a  
 //Cat{name:"Black Cat",showName: function(){ alert(this.name);}  At this time this.name 
 // for this.name=Cat.name, So for Black Cat . 


Related articles: