What are the benefits of returning a function as a return value?

such as the title: often see other people writing code like to return the function as a return value

    var res = test()
    console.log((res.next())())
    function test() {
        var a = 10;
        return {
            next(){
                return function () {
                    return a+1
                }
            }
        }
    }
    

I think writing like this will solve the problem:

var res = test()
console.log(res)
function test() {
    var a = 10;
    return a+1
}   

what are the advantages of the first way of writing? What are the usage scenarios?

Jul.08,2022

he will add you every time the next value is 11


this actually belongs to the callback function, that is, the callback function, which sets a function to trigger when certain conditions are met. There are widely used scenarios where the front-end interface is used to receive data and other data interaction. For example, ajax is a callback function when it is used to receive data. Such is the property assigned by the xhr.onreadystatechange in the figure.

this string of code is the login scenario, in which callback is used for data monitoring and processing.


this can be used as a closure, and the value of an is always the value after running.

but it's strange why another function is returned in next. In fact, you only need to return next.


higher order function, encapsulating complex method processing parameters using
function Corialization

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1c05e41-327d0.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1c05e41-327d0.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?