简体   繁体   English

生成器并在浏览器外“产生”

[英]Generators and “yield” outside the browser

This is snippet is found here , in an MDN article describing generators and iterators in JavaScript. 这是片断被发现在这里 ,一个MDN文章描述的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 yield关键字仅适用于包含在HTML中的HTML中的代码块

<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. 实际上,当嵌入HTML文件并包含在上述标签中时,该片段工作正常。 The problem is, I tried it in Rhino and it doesn't seem to work outside HTML and the browser. 问题是,我在Rhino中尝试过,它似乎不能在HTML和浏览器之外工作。

So how can I use generators outside the browser? 那么如何在浏览器之外使用生成器呢?

https://developer.mozilla.org/en/New_in_Rhino_1.7R1#JavaScript_1.7_features 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. 要启用JavaScript 1.7支持,必须使用Context.setLanguageVersion() API调用将版本设置为170。 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. 如果您使用的是Rhino shell,则可以在命令行中指定-version 170 ,或者在shell执行的代码中调用version(170)

To change context: 要改变背景:

            Context ctx = Context.enter();
            ctx.setLanguageVersion(Context.VERSION_1_7);
            try {

             CompilerEnvirons compEnv = new CompilerEnvirons();
             compEnv.initFromContext(ctx);

             ...

            }
            finally { Context.exit(); }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM