javascriptfirefoxrhino

Generators and "yield" outside the browser


This is snippet is found here, in an MDN article describing generators and iterators in JavaScript.

function simpleGenerator(){  
  yield "first";  
  yield "second";  
  yield "third";  
  for (var i = 0; i < 3; i++)  
    yield i;  
}  

var g = simpleGenerator();  
print(g.next()); // prints "first"  
print(g.next()); // prints "second"  
print(g.next()); // prints "third"  
print(g.next()); // prints 0  
print(g.next()); // prints 1  
print(g.next()); // prints 2  
print(g.next()); // StopIteration is thrown  

Above that we read:

The yield keyword is only available to code blocks in HTML wrapped in a

<script type="application/javascript;version=1.7">

block (or higher version).

Indeed, the snippet works fine when embedded in an HTML file and included in the aforementioned tag. The problem is, I tried it in Rhino and it doesn't seem to work outside HTML and the browser.

So how can I use generators outside the browser?


Solution

  • https://developer.mozilla.org/en/New_in_Rhino_1.7R1#JavaScript_1.7_features

    To enable JavaScript 1.7 support, you must set the version as 170 using the Context.setLanguageVersion() API call. If you are using the Rhino shell, you can specify -version 170 on the command line or call version(170) in code executed by the shell.