Created
May 4, 2015 03:51
-
-
Save coolicer/b71ebf9107c6deb5bd9a to your computer and use it in GitHub Desktop.
learn es6
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
1. Generator | |
可以暂停,可以重新运行。在内部暂停,在外部重新启动 | |
普通函数只是一开始接收参数,至完成时返回。yield 返回信息,send发送信息重启 | |
*/ | |
function *foo() { | |
/* | |
generator跟普通函数差不多,只是多了一个*号表示这是一个generator函数。 | |
主要的还是yield这个关键字 | |
yield ____ : "yield表达式" | |
*/ | |
} | |
function * foo() { | |
var x = 1 + (yield "foo"); | |
console.log(x); | |
} | |
/* | |
yield "foo" 这个表达式会把"foo"这个字符串返回并暂停, | |
当函数重启,无论传入什么都会作为它的结果 | |
out -----> "foo" | |
in <---- 1 + "foo" | |
*/ | |
// note: `foo(..)` here is NOT a generator!! | |
function foo(x) { | |
console.log("x: " + x); | |
} | |
function *bar() { | |
yield; // just pause | |
foo( yield ); // pause waiting for a parameter to pass into `foo(..)` | |
} | |
/* | |
一个有趣的例子,如果yield传空,默认为yield undefined, | |
那么,当2次next过后,现调用foo,结果为 "x: undefined" | |
*/ | |
function *foo() { | |
yield 1; | |
yield 2; | |
yield 3; | |
yield 4; | |
yield 5; | |
} | |
/* | |
调用这个generator,就像调用普通的函数,但是却没有使用new关键字。 | |
尽管看起来像一个构造器, var f = foo(). | |
f.next(), 返回一个对象 | |
*/ | |
function *foo(x) { | |
/*1*/ var y = 2 * (yield (x + 1)); | |
/*2*/ var z = yield (y / 3); | |
/*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 } | |
/* | |
一个综合的例子 | |
就像前面说的,generator会yield后返回对象,当send(相当于next)的时候又可以传回数据 | |
当调用第一个next,yield返回 { value:6, done:false }, 函数暂停 | |
当第二个next调用,参照上面『当函数重启,无论传入什么都会作为它的结果』 | |
var y = 2 * 12,所以y = 24, yield返回 24/3=>{ value:8, done:false } | |
第三个next,var z = 13, yield返回 { value:42, done:true } | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment