JavaScript为什么要在函数中返回函数? [英] JavaScript Why return function in a function?

查看:138
本文介绍了JavaScript为什么要在函数中返回函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  var favoriteColor =blue; 
函数colorGenerator(color){
return function(){return color; };
}
var getColor = colorGenerator(favoriteColor);

为什么getColor不是蓝色。 getColor()是蓝色的。 getColor也成为一个函数?因为我们在colorGenerator中返回一个函数?

我对这些感到困惑。感谢您的帮助。

解决方案

Javascript具有一流的功能,这意味着函数可以像任何其他参数或变量一样传递,甚至可以返回函数 - 根据您的示例。



当您调用 getColor 时,您将返回一个函数,因为它就是这样(当你调用 getColor()时,你正在执行该函数,并获取字符串返回值值blue;

在您的具体情况中,深入一点, colorGenerator 实际上是一个身份生成器
在函数式编程中,一个标识只是一个返回它的原始输入的函数。它在功能风格的编程中很有用,也就是组合。



无论您是否尝试使用功能样式都不清楚,所以我会强烈阻止推荐这本免费的在线图书功能丰富的编程指南
这很容易从新手到专业人士消化和涵盖此事。
如果您想进一步学习,我会通过 JavaScriptAllongé进行跟进,免费的JavaScript书籍,涵盖函数式编程。

var favoriteColor = "blue";
function colorGenerator(color) {
    return function () { return color; };
}
var getColor = colorGenerator(favoriteColor);

Why getColor is not blue. getColor() is blue. getColor also becomes a function? Because we return a function in colorGenerator?

I am confused about these. Thank you for your help.

解决方案

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.

这篇关于JavaScript为什么要在函数中返回函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆