Three ways of writing callback function in JS

Source: Internet
Author: User

Three ways to type a callback function:

1. Call by pointer

2. Call by anonymous function

3, the definition and execution at the same time

          //to invoke by a pointer            functionMath (num1,num2,callback) {returncallback (NUM1, num2); }            functionAA (num1,num2) {returnNUM1 +num2; }            functionBB (num1,num2) {returnNUM1-num2; } console.log (Math (2,1,AA));//3Console.log (Math (2,1,BB));//1                                    //by anonymous function calls (essentially the same as in the first way)            functionMath (num1,num2,callback) {returncallback (NUM1,NUM2); } console.log (Math (2, 1,function(num1,num2) {returnNUM1 +num2; })            ); //3                                    //definition and execution at the same time (self-executing)(function(num) {console.log (num); } )(1);//1

the function of the callback function : You can write the tool method for external use (the argument is logically processed, and then return the result directly to the callback function is OK)

// processing the input parameter, outputting the result to the callback function for external use        function Parsestr (param,callback) {            var result = param + ' very handsome ';            Callback (result);        }        Parsestr (' Xu Wenxiang ',function(result) {            console.log (result);   // Xu Wenxiang very handsome        })

 

Three ways of writing callback function in JS

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.