1. 程式人生 > >ES6知識點整理之----Generator----其他

ES6知識點整理之----Generator----其他

應用 控制流 上下 method pre next fine cti 生成

1、如果一個對象的屬性是 Generator 函數,可以簡寫成下面的形式。

let obj = {
  * myGeneratorMethod() {
    ···
  }
};

2、Generator 函數總是返回一個遍歷器,這個遍歷器是 Generator 函數的實例,也繼承了 Generator 函數的prototype對象上的方法。

3、Generator 函數不能跟new命令一起用,會報錯。

3、Generator 函數返回一個正常的對象實例,既可以用next方法,又可以獲得正常的this

function* F() {
  this.a = 1;
  yield this.b = 2;
  yield 
this.c = 3; } var obj = {}; //使用call方法綁定Generator函數內部的this var f = F.call(obj); f.next(); // Object {value: 2, done: false} f.next(); // Object {value: 3, done: false} f.next(); // Object {value: undefined, done: true} obj.a // 1 obj.b // 2 obj.c // 3

4、將 執行的是遍歷器對象f 和 生成的對象實例obj 統一

function* F() {
  this.a = 1;
  yield 
this.b = 2; yield this.c = 3; }

// 將空對象obj 換成 F.prototype
var f = F.call(F.prototype); f.next(); // Object {value: 2, done: false} f.next(); // Object {value: 3, done: false} f.next(); // Object {value: undefined, done: true} f.a // 1 f.b // 2 f.c // 3

5、將F改成構造函數,對它執行new 命令

function* gen() {
  this.a = 1;
  yield 
this.b = 2; yield this.c = 3; } function F() { return gen.call(gen.prototype); } var f = new F(); f.next(); // Object {value: 2, done: false} f.next(); // Object {value: 3, done: false} f.next(); // Object {value: undefined, done: true} f.a // 1 f.b // 2 f.c // 3

6、Generator 與狀態機。Generator 之所以可以不用外部變量保存狀態,是因為它本身就包含了一個狀態信息

var clock = function* () {
  while (true) {
    console.log(‘Tick!‘);
    yield;
    console.log(‘Tock!‘);
    yield;
  }
};

7、Generator 與協程(暫略)

8、Generator 與上下文。(暫略)

9、應用:

  • 異步操作的同步化表達
  • 控制流管理
  • 部署Iterator接口
  • 作為數據結構

ES6知識點整理之----Generator----其他