Why use closure in that simple case?

泪湿孤枕 提交于 2019-12-24 10:47:49

问题


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.



来源:https://stackoverflow.com/questions/9753382/why-use-closure-in-that-simple-case

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!