赞
踩
使用一个变量维护状态
let open = true
let clock = () => {
open = !open
return !open
}
console.log(clock())
console.log(clock())
使用generator自身状态
let clock2 = function* () {
while(true) {
yield true
yield false
}
}
let gen = clock2()
console.log(gen.next().value)
console.log(gen.next().value)
console.log(gen.next().value)
console.log(gen.next().value)
控制状态机1:使用互相来控制
let clock3 = function* () { let r while(r = (yield 'isOpen?')) { yield true yield false } } let r let gen = clock3() gen.next() // 启动 r = gen.next(1) // t 开启 console.log(r.value) r = gen.next() // f console.log(r.value) r = gen.next() // ask console.log(r.value) r = gen.next(1) // t 开启 console.log(r.value) r = gen.next() // f console.log(r.value) r = gen.next() // ask console.log(r.value) r = gen.next(0) // 关闭 console.log(r.value) r = gen.next() // undefined console.log(r.value) r = gen.next() // undefined console.log(r.value)
控制状态机2:使用return来控制
let clock4 = function* () { while(true) { yield true yield false } } let r let gen = clock4() r = gen.next() // t console.log(r.value) r = gen.next() // f console.log(r.value) r = gen.return() // undefined console.log(r.value) r = gen.next() // undefined console.log(r.value)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。