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
I think its just a simple example to illustrate the concepts of closures.
It gives more flexibility. This case is simplified enough, but in more complicated situations you may need it.
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.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
andname
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 callgreet
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.