JavaScript Why return function in a function?

前端 未结 6 1679
青春惊慌失措
青春惊慌失措 2020-12-18 04:17
var favoriteColor = \"blue\";
function colorGenerator(color) {
    return function () { return color; };
}
var getColor = colorGenerator(favoriteColor);
6条回答
  •  一向
    一向 (楼主)
    2020-12-18 04:47

    It's called making a closure. Basically for each call of that colorGenerator function the vars local to it will stay around and be represented in the call of the function it returns.

    See this:

    function colorGenerator(color) {
        return function () { return color; };
    }
    
    // remember these are functions to be called, not the actual color names
    var getRed = colorGenerator('red');
    var getBlue = colorGenerator('blue');
    
    // now each time we call the returned function of
    // each, it will say the color we want
    alert( getRed() + " and " + getBlue() ); // -> "red and blue"
    

    I don't know the context of this snippet of code, so why you'd basically need a factory for making functions that return a certain color name, I don't know. But that's essentially what it'll do.

    For explaining why that would be useful in a certain context we'd probably have to know the context...

提交回复
热议问题