JavaScript Why return function in a function?

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

    Javascript has first-class functions, meaning that functions can be passed around like any other argument or variable, you can even return functions - as per your example.

    when you call getColor, you'll get back a function because that's what it is (colorGenerator returns a function).

    When you call getColor() you're executing that function, and getting the string return value "blue";

    Delving a little deeper, in your specific case, colorGenerator is in fact an identity generator. In functional programming, an identity is simply a function that returns it's original input. It is useful in functional-style programming, namely composition.

    Whether you are trying to use a functional style or not isn't clear, so I'll stop by strongly recommending this free online book Mostly adequate guide to functional programming It is very easy to digest and covers the matter from newcomer to pro. If you want to go further, I'd follow-through with Javascript Allongé, another great free JavaScript book which covers functional programming.

提交回复
热议问题