0

So i was watching this video and at 18:14 he has an example showcasing closures in the programming language "Groovy". https://www.youtube.com/watch?v=7aYS9PcAITQ

Can JavaScript "save" instances in the same way using closures and if so, could somebody wrap up a little codesample for me to study? I've been reading up on closures in JavaScript and essentially i know that if you have a function within a function and the outer function returns the inner function can be kept alive and that's part of what a closure is.

def makeCounter() {
    def very_local_variable = 0
    return { very_local_variable += 1 }
}

c1 = makeCounter()
c1()
c1()
c1()

c2 = makeCounter()

println "C1 = ${c1()}, C2 = ${c2()}"

OUTPUT and closures:
C1 = 4, C2 = 1
Sauceman
  • 147
  • 6
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures – m59 Dec 30 '13 at 22:50
  • Javascript does have closures, and a quick Google search will tell you how they work, as we're not really interested in seeing some pseudo random code that has nothing to do with the question. – adeneo Dec 30 '13 at 22:51
  • I'm amused because http://stackoverflow.com/questions/111102/how-do-javascript-closures-work?rq=1 almost always shows up as the top Related question in Javascript questions, but it's usually unrelated. This time it really _is_. – Barmar Dec 30 '13 at 22:55
  • The code in the question is relevant, and its origin was explained. – cookie monster Dec 30 '13 at 23:01

1 Answers1

3
function makeCounter() {
    var very_local_variable = 0;
    return function() { return very_local_variable += 1; };
}

var c1 = makeCounter();
c1();
c1();
c1();

var c2 = makeCounter();

console.log("C1 = ", c1(), " C2 = ", c2());
cookie monster
  • 10,671
  • 4
  • 31
  • 45