Why use closure in that simple case?

2019-07-27 05:26发布

问题:

In this article http://howtonode.org/why-use-closure an example is given :

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();

Why would it be more worth than

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 ?

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

回答1:

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.

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.

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.



回答2:

Watch this video, http://pyvideo.org/video/880/stop-writing-classes, although its in Python the concepts are transferrable. Usually if you have a class that has one function, its overkill.



回答3:

It gives more flexibility. This case is simplified enough, but in more complicated situations you may need it.



回答4:

I think its just a simple example to illustrate the concepts of closures.