0

I see Javascript closures as functions with local states, which appears to be the same thing as generators.

  1. What's the difference between a closure and a generator?
  2. What would make one a more fitting tool than another for some context?
Meow
  • 1,610
  • 1
  • 14
  • 18
  • They do completely different things. – SLaks Jun 01 '16 at 03:24
  • What can a closure do that a generator cannot? They both take an input, do something with respect to an internal state, and execute / return a response, or am I mistaken? – Meow Jun 01 '16 at 03:25
  • A closure can contain multiple functions that can be called arbitrarily with arbitrary parameters. A generator can only be resumed sequentially until it terminates – SLaks Jun 01 '16 at 03:30
  • Yes, apart from the minor difference that a closure only can be called but a generator object has three different methods that can be invoked on it, they are similar in concept. But have a look at their definitions - replicating the behaviour of a non-trivial generator function is almost impossible with a closure-generating function (by hand). – Bergi Jun 01 '16 at 03:30

0 Answers0