javascript - What's the difference between "new" and directly invoking a generator function? -
i know difference between "new" , directly invoking normal function.
but how case 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 same?
generators allow define iterative algorithm writing single function can maintain own state.a generator special type of function works factory iterators. function becomes generator if contains 1 or more yield expressions.when generator function called body of function not execute straight away; instead, returns generator-iterator object. each call generator-iterator's next() method execute body of function next yield expression , return result. when either end of function or return statement reached, stopiteration exception thrown. generator function can used directly iterator method of class, reducing amount of code needed create custom iterators.
function range(low, high){ this.low = low; this.high = high; } range.prototype.__iterator__ = function(){ (var = this.low; <= this.high; i++) yield i; }; var range = new range(3, 5); (var in range) print(i); // prints 3, 4, 5 in sequence
not generators terminate; possible create generator represents infinite sequence.
Comments
Post a Comment