What is the difference between a "new" and a direct call to a generator function?

I know the difference between a "new" and a direct call to a normal function.

But what about the case for the generator function?

eg:

function *counter(){ let n = 0; while (n < 2) { yield n++; } return 10; } var countIter1 = new counter(); var countIter2 = counter(); 

It seems they are the same?

+7
javascript generator ecmascript-harmony
source share
1 answer

Generators allow you to define an iterative algorithm by writing a single function that can maintain its own state. A generator is a special type of function that works like a factory for iterators. A function becomes a generator if it contains one or more output expressions. When calling the generator function, the function body is not executed immediately; instead, it returns an iterator-generator object. Each call to the generator-iterator next () method executes the function body until the next yield expression and returns its result. When either the end of the function or the return statement is reached, a StopIteration exception is thrown. The generator function can be used directly as a class iterator method, which significantly reduces the amount of code required to create custom iterators.

  function Range(low, high){ this.low = low; this.high = high; } Range.prototype.__iterator__ = function(){ for (var i = this.low; i <= this.high; i++) yield i; }; var range = new Range(3, 5); for (var i in range) print(i); // prints 3, then 4, then 5 in sequence 

Not all generators end; You can create a generator that represents an infinite sequence.

+1
source share

All Articles