I know the difference between "new" and directly invoking a normal function.
But how about the case for the generator function?
e.g:
function *counter(){
let n = 0;
while (n < 2) {
yield n++;
}
return 10;
}
var countIter1 = new counter();
var countIter2 = counter();
seems they're the same?
The function* declaration ( function keyword followed by an asterisk) defines a generator function, which returns a Generator object.
Generator functions are defined using the * asterisk either immediately after the function keyword or right before the function name. The below example creates an infinite number of natural numbers, which can be used when needed. We can use the yield* to call another generator from within a generator.
To finish the execution of the generator function, we can use the return statement. Returned value will be used to set the value property of the object returned by the generator.
Generators allow you to define an iterative algorithm by writing a single function which can maintain its own state.A generator is a special type of function that works as a factory for iterators. A function becomes a generator if it contains one or more yield expressions.When a generator function is called the body of the function does not execute straight away; instead, it returns a generator-iterator object. Each call to the generator-iterator's next() method will execute the body of the function up to the next yield expression and return its result. When either the end of the function or a return statement is reached, a StopIteration exception is thrown. A generator function can be used directly as the iterator method of a class, greatly reducing the amount of code needed 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 terminate; it is possible to create a generator that represents an infinite sequence.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With