JavaScript Why return function in a function?

前端 未结 6 1683
青春惊慌失措
青春惊慌失措 2020-12-18 04:17
var favoriteColor = \"blue\";
function colorGenerator(color) {
    return function () { return color; };
}
var getColor = colorGenerator(favoriteColor);
6条回答
  •  星月不相逢
    2020-12-18 05:02

    Hopefully this example can help you to understand how to use the return function

    The following example illustrates the use of the return statement to return a function.

    JavaScript

    function doWork() {
        return function calculate(y) { return y + 1; };
    }
    
    var func = doWork();
    var x = func(5);
    document.write(x);
    
    // Output: 6
    

    PS:
    return[(][expression][)];

    The optional expression argument is the value to be returned from the function.If omitted, the function does not return a value.
    You use the return statement to stop execution of a function and return the value of expression.If expression is omitted, or no return statement is executed from within the function, the expression that called the current function is assigned the value undefined.

提交回复
热议问题