每天學點ES6 —— 可暫停的函數 Generator

已發ES6文章:

概念

Generator 函數是可暫停的函數,它返回一個遍歷器對象,通過遍歷器對象可以繼續執行。

注:一般的函數只能返回一次值,而Generator 函數可以分次返回多個值

定義和使用

類似普通函數的定義,但是需要在函數名稱前加一個 * 號,函數體內使用 yield 語句定義各個暫停點。

Generator 函數使用跟普通函數一樣執行,返回一個遍歷器對象。

function * myGenerator(){

 yield 'a';

 yield 'b';

 return 'c';

}

var g=myGenerator();

g.next(); //{value: "a", done: false}

g.next(); //{value: "b", done: false}

g.next(); //{value: "c", done: true}

yield 語句

yield 表示暫停的意思,使用next方法執行下一條 yield 語句,直到retrun為止(沒有return返回undefined)

yield 不可使用在普通函數里,Generator 函數中yield就是暫停的標識。

注:

1. yield 語句無返回值(undefined)。

2. Generator函數內部調用另一個Generator函數,需要使用 yield * 語句

Generator 函數注入值

next可以帶一個參數,該參數在 Generator 內部作為上一次 yield 語句的返回值。

function * gen(x){

 let result=yield (x+1);

 return result+1;

}

let g=gen(1);

g.next(); //{value: 2, done: false}

g.next(); //{value: NaN, done: true}

//第一步yield 1+x返回值為undefined

//第二步結果是 1+undefined

//可以給next傳參

let gg=gen(1);

gg.next(); //{value: 2, done: false}

gg.next(1); //{value: 2, done: false}

//第一步yield 1+x返回值為undefined

//第二步next傳參被認為是第一步的返回值,即為1

注:由於第一次使用next方法,沒有上一個yield語句,所有next傳值無效

Generator的方法

1. throw(e)

Generator 函數內部的try catch拋出錯誤則會終止執行。使用throw方法可以讓內部的try catch捕獲錯誤。

function * g(x){

 try{

  yield 2;

  yield x.name;

  yield 3;

 }catch(e){

  console.log('非法值',e)

 }

};

var cc=g();

cc.next();

cc.next(); //報錯 {value: undefined, done: true}

var ccc=g();

ccc.next();

ccc.throw('ss'); //非法值 ss {value: undefined, done: true}

2. return(x)

return 方法用來結束函數,x作為返回值

function * g(){

 yield 1;

 yield 2;

 yield 3;

}

var cc=g();

cc.next(); //{value: 1, done: false}

cc.return('cc'); //{value: "cc", done: true}

cc.next(); //{value: undefined, done: true}

Generator 函數中的this

Generator函數返回的是一個遍歷器,且這個遍歷器是Generator函數實例,但函數的this不指向構造函數本身

function * g(){

this.aaa=1;

}

var cc=g();

cc instanceof g; //true

cc.next();

cc.aaa; //undefined

window.aaa; //1

文章到這裡結束,下篇 ☞ Promise

【關注一下不迷路~】

每天學點ES6 ——  可暫停的函數 Generator

【html】【css】【html】【css】【javascript】【html】【javascript】【css】【javascript】【css】


分享到:


相關文章: