为什么在这种简单的情况下使用闭包?

编程入门 行业动态 更新时间:2024-10-11 23:16:19
本文介绍了为什么在这种简单的情况下使用闭包?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

本文 howtonode/why-use-closure 示例

function greeter(name, age) { var message = name + ", who is " + age + " years old, says hi!"; return function greet() { console.log(message); }; } // Generate the closure var bobGreeter = greeter("Bob", 47); // Use the closure bobGreeter();

为什么会比

function greeter(name, age) { var message = name + ", who is " + age + " years old, says hi!"; console.log(message); } greeter("Bob", 47);

这样更短,显然是一回事吗?

which is much shorter and does apparently the same thing ? Or it doesn't ?

更新2:对于这种情况,它可能是有用的解决js中getter的丑陋语法

Update 2: could it be usefull somehow for this case Solving ugly syntax for getter in js

推荐答案

它不做同样的事情。第二个示例强制您立即打印输出,而第一个允许您延迟输出。

It does not do the same thing. The second example forces you to print the output right on the spot, while the first one allows you to delay it.

换句话说:在第一种情况下,您不需要在范围中具有 age 和 name 的地方打印输出;在第二个例子中,你做。

To put it another way: in the first case, you do not need to print the output right at the point where you have age and name in scope; in the second example, you do.

当然,你需要以某种方式transport bobGreeter 你实际上在其上调用 greet 的范围,并且需要传输1个值而不是2值不是最有说服力的参数。但记住,在一般情况下,它是1对N。

Of course it's true that you need to somehow "transport" bobGreeter to the scope where you will actually call greet on it, and needing to transport 1 value instead of 2 is not the most compelling argument. But remember that in the general case it's 1 against N.

还有许多其他原因使闭包引人注目,不能用这个特定的例子说明。

There there are also many other reasons that make closures compelling that cannot be illustrated with this particular example.

更多推荐

为什么在这种简单的情况下使用闭包?

本文发布于:2023-11-15 09:33:05,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1593244.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:在这种   情况下   简单

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!