generator的一些語法

紫Young菌發表於2018-04-28
  1. Generator.prototype.return() :Generator 函式返回的遍歷器物件,還有一個return方法,可以返回給定的值,並且終結遍歷 Generator 函式。
function* gen() {
  yield 1;
  yield 2;
  yield 3;
}

var g = gen();

g.next()        // { value: 1, done: false }
g.return('foo') // { value: "foo", done: true }
g.next()        // { value: undefined, done: true }
複製程式碼
  1. Generator.prototype.throw():Generator 函式返回的遍歷器物件,都有一個throw方法,可以在函式體外丟擲錯誤,然後在 Generator 函式體內捕獲。
var g = function* () {
  try {
    yield;
  } catch (e) {
    console.log('內部捕獲', e);
  }
};

var i = g();
i.next();

try {
  i.throw('a');
  i.throw('b');
} catch (e) {
  console.log('外部捕獲', e);
}
// 內部捕獲 a
// 外部捕獲 b
複製程式碼
  1. generator函式的this generator函式總是返回一個遍歷器,利es6規定這個遍歷器是generator函式的例項,也繼承了該函式的原型物件上的方法。
function* g() {}

g.prototype.hello = function () {
  return 'hi!';
};

let obj = g();

obj instanceof g // true 說明object是g的例項
obj.hello() // 'hi!' 
複製程式碼

但是g返回的是遍歷器物件,而不是this物件,例如下:

function* g() {
  this.a = 11;
}

let obj = g();
obj.a // undefined 不能返回this
複製程式碼

不是純粹的建構函式,不能用new命令來跟建構函式一起使用。既想用next又想使用this,變通方法如下:

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

//執行過程中,一步步將屬性繫結在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
複製程式碼

但是上面程式碼執行的是f(遍歷器),生成的是例項obj,為了實現這兩個物件統一。將obj換成F.prototype

function* F() {
  this.a = 1;
  yield this.b = 2;
  yield this.c = 3;
}
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
複製程式碼

相關文章