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  
father(son);      //Call back the son function  
father(son1);     //Send son1 function and call back son1 function

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

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

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

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);,name);  
var fa = new father("tank");  
fa.showFatherName('son');     //When transferring strings, when using callbacks, use eval to convert them  

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

3. Callback in the domain

var son = {  
       this.fathername();    //Play father;  
       alert(;     //Play tank  
var father = {  
       _callback = eval(_callback);  

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