5、简写与this
5.1、简写
Generator函数的写法有三种(除了第一种名字都自己捏的):
- 声明式;
- 赋值式;
- 属性式;
其中,属性式除了常规写法外,还有简写版(就像当函数作为对象属性时的简写一样)。
如代码,一目了然:
// 声明式
function *g1() {
yield 'g1'
}
// 赋值式
let g2 = function*() {
yield 'g2'
}
// 属性式
let foo = {
g3: function*() {
yield 'g3'
},
// 简写的属性式
*g4(){
yield 'g4'
}
}
for (let i of g1()) {
console.log(i)
}
// g1
for (let i of g2()) {
console.log(i)
}
// g2
for (let i of foo.g3()) {
console.log(i)
}
// g3
for (let i of foo.g4()) {
console.log(i)
}
// g4
5.2、this
Generator函数的this指向谁呢?
答案是window,如代码:
function *g1() {
console.log(this)
yield 'g1'
}
let foo = g1()
foo.next()
// Window
// {value: "g1", done: false}
由于Generator函数不能通过new来生成遍历器(会报错),因此显然通过这条路来改变this的指向显然是走不通的。
那么如何改变Generator的this指向的目标呢?
答案很简单:
- apply或者call;
- bind
使用bind的示例如下:
function *g1() {
console.log(this)
yield 'g1'
}
g1 = g1.bind("g1")
let foo = g1()
foo.next()
// 'g1'
// {value: "g1", done: false}
call的示例:
function *g1() {
console.log(this)
yield 'g1'
}
let foo = g1.call("g1")
foo.next()
// 'g1'
// {value: "g1", done: false}
遍历器调用更多的方法
遍历器通常只能调用next、throw、return。
假如想调用更多的呢?
简单解决办法是通过原型链来完成,示例如下:
function *g() {
yield 'g1'
}
g.prototype.getDate = function () {
return new Date()
}
let foo = g()
foo.getDate()
// Tue Aug 22 2017 00:06:26 GMT+0800 (CST)
在遍历器里调用更多方法并且能操作this
简单来说,就是假如我遍历器想要添加count和add两个方法,分别是获取当前计数和对计数增加。
如果分别是独立的,那么很简单,通过上面来完成即可。
但假如需要操作Generator函数内部的变量呢?由于Generator函数不能通过new来生成实例,因此要复杂一些。
具体思路是让Generator函数的this,指向他本身的prototype原型链,于是当调用this的时候,自然相当于this指向了原型链,可以调用原型链上的属性。
如代码:
function Foo() {
function *g() {
yield 'g1'
}
g.prototype.number = 0;
g.prototype.count = function () {
return this.number
}
g.prototype.add = function (val) {
this.number += val;
return this.number;
}
let foo = g.call(g.prototype)
return foo;
}
let bar = new Foo();
另外:
- new Foo与直接Foo()没什么区别,都是返回一个新的Generator遍历器;
- 虽然不能通过new g()来生成,但实质上,通过g()生成的遍历器对象,他们原型链上的number的状态,并不共享(独立的,互不干扰);