1

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

Community
  • 1
  • 1
user310291
  • 36,946
  • 82
  • 271
  • 487
  • I wouldn't get caught up in the specific example. They are trying to make it easy to digest. Imagine if you wanted to keep track of a lot more complex state. That's when it becomes truly useful. – ChaosPandion Mar 17 '12 at 20:23
  • This is just an example of someone overthinking closures. Completely useless. – Dagg Nabbit Mar 17 '12 at 20:23
  • :) yeah then could someone give a similar but more real world example – user310291 Mar 17 '12 at 20:26
  • A deeper explanation of closures & why @ http://stackoverflow.com/questions/9578441/javascript-closures/9578477#9578477 – bryanmac Mar 17 '12 at 20:27

4 Answers4

5

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.

Jon
  • 428,835
  • 81
  • 738
  • 806
  • The author gives other examples which are great. It's just the first one which is too simplistic :) – user310291 Mar 17 '12 at 20:30
  • could it be usefull somehow for this case http://stackoverflow.com/questions/9777856/solving-ugly-syntax-for-getter-in-js – user310291 Mar 19 '12 at 21:04
1

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.

Doboy
  • 10,411
  • 11
  • 40
  • 48
1

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

simon
  • 1,161
  • 10
  • 27
0

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

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445