Definition: The argument or return value of a function is still a function

Application 1: after function.

The after function takes two arguments, the first to call back the function, and the second to call back the function when it is executed several times.

let after = function (myfunc,times) {
        var time = times;
        return function () {
            time--;
            if(time<=0){ myfunc(); }}}var my = function () {
        console.log("Function executed.");
    }
    var aaa = after(my,3);
    aaa();
    aaa();
    aaa();
    aaa();
Copy the code

The function above prints “the function was executed,” passes it to the after function, and specifies three times after the callback is executed. Now that AAA has been called four times, only the third and fourth calls will actually print “function executed.” The print result is as follows:

Application 2: before function

When the before function of a function (myFunctuin) is called, the parameter is a callback function, which should be executed before myFunction is executed, as follows:

    Function.prototype.before = function (myFun) {
        let that = this;
        return function () { myFun(); that(); }}let myFun = function () {
        console.log("I am myFun");
    }
    let insert = function () {
        console.log("I should do it before myFun.");
    }
    let aaa = myFun.before(insert);
    aaa();
Copy the code

The result is as follows: