Three uses of js callback function

js callback function has the following three usages,
1. Direct callback
2. call callback
3. apply callback
The callback function works properly, reduces code redundancy, enhances code readability, and makes code maintenance much easier.


What do you want to use the callback function?
When there are many places that need to call the same function, and this function does different processing according to different needs, it is particularly appropriate to use the callback function at this time.


1, Direct callback

function son () {  
 alert('tank test');  
}  
  
function son1 () {  
 alert('tank test1');  
}  
  
function father (callback) {   //Common function  
 callback();  
 callback.call();  
}  
  
father(son);      //Call back the son function  
father(son1);     //Send son1 function and call back son1 function

The function of callback(),callback.call() is the same without parameters.


2, call and apply callbacks
1. Difference between call and apply

call([thisObj[,arg1[, arg2[, [,.argN]]]]])   
  
apply([thisObj[,argArray]])

call and apply are basically the same, but the syntax is different. thisobj can inherit and replace this object in the target function, as shown in the following example.

2. Callback in method class

function son(name){  
   this.sonName = name;  
   this.showSonName = function(){  
       alert(this.sonName);       //Pop up tank  
       alert(this.fatherName);    //Pop up the parent. This is the attribute in the parent. Do you have the feeling of PHP extensions  
   }  
}        
  
function father(name){  
   this.fatherName = 'father';  
   this.showFatherName = function(_callback){  
       _callback = eval(_callback);  
       _callback.call(this,name);  
       //_callback.apply(this,Array(name));  
   }  
}        
  
var fa = new father("tank");  
fa.showFatherName('son');     //When transferring strings, when using callbacks, use eval to convert them  
fa.showSonName();

When using call for callback, this method in call will inherit son's method and replace


3. Callback in the domain

var son = {  
   name:"son",  
   getname:function(name){  
       this.fathername();    //Play father  
       this.name=name;  
       alert(this.name);     //Play tank  
   }  
}  
  
var father = {  
   init:function(_callback,name){  
       _callback = eval(_callback);  
       _callback.apply(this,Array('tank'));  
   },  
   fathername:function(){  
       alert('father');  
   }  
}  
  
father.init('son.getname');

When using apply for callback, this method in apply will inherit son's method and replace


Tags: Attribute PHP

Posted on Sun, 03 May 2020 08:57:56 -0400 by aeroswat