为什么在这种简单的情况下使用闭包? [英] Why use closure in that simple case?

查看:152
本文介绍了为什么在这种简单的情况下使用闭包?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

本文 http://howtonode.org/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.

这篇关于为什么在这种简单的情况下使用闭包?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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