【发布时间】:2014-12-28 23:51:12
【问题描述】:
对于 ES6 生成器,为什么this blog post 的作者说:
来自:http://davidwalsh.name/es6-generators
“第一次 next(..) 调用,我们没有发送任何东西。为什么?因为没有 yield 表达式来接收我们传入的内容。”
不是第一个it.next() 调用(yield (x + 1))吗?
function *foo(x) {
var y = 2 * (yield (x + 1));
var z = yield (y / 3);
return (x + y + z);
}
var it = foo( 5 );
// note: not sending anything into `next()` here
console.log( it.next() ); // { value:6, done:false }
console.log( it.next( 12 ) ); // { value:8, done:false }
console.log( it.next( 13 ) ); // { value:42, done:true }
您可以看到,我们仍然可以通过初始 foo(5) 迭代器实例化调用传入参数(在我们的示例中为 x),就像使用普通函数一样。
第一个 next(..) 调用,我们不发送任何东西。为什么?因为没有 yield 表达式来接收我们传入的内容。
【问题讨论】:
标签: javascript ecmascript-6 ecmascript-harmony