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

Menu