秦皇岛做网站的公司选汉狮,惠州市网站设计公司,移动网站 案例,动漫制作专业专科学校首先看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操作符,
下面一共一个解决…首先看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