首先看2個例子
function * g() {this.a = 11;
}let o = g();
console.log(o.a);
可以看見Generator函數里面的this指向的對象取不出來.
再看下一個例子:
function* F() {yield this.x = 2;yield this.y = 3;
}
new F();
可以看出Generator函數無法使用new操作符,
下面一共一個解決方案:使之可以使用new 和 將this對象正確取出來
function* gen() {this.a = 1;yield this.b = 2;
}// 傳入gen的原型對象,并使用call方法綁定作用域..可以解決this作用域問題
// 將F改造成構造函數的形式可以解決new 問題
function F() {return gen.call(gen.prototype);
}var f = new F();
console.log(f.next());
console.log(f.next());
console.log(f.a);
console.log(f.b);
可以看到.并沒有報錯,并且this正確綁定到實例f上了.f也可以使用next方法.
參考《ES6標準入門》(第三版) P343~P345