js 生成器 Generator 用法随笔

生成器对象是由一个 generator function 返回的,并且它符合可迭代协议和迭代器协议1

示例

function* Father() {
    
    
	yield 'a';
	yield 'b';
	yield 'c';
}

var son = Father()
son.next()

function*

语法就是有个 * 号, 没什么可以解释


yield

yield 的作用有点像 return
调用 next() 就执行到 yield 并返回它后面的内容
第二次调用 next() 就从上次返回的地方继续执行, 直到下一个 yield
next() 到最后, 没有 yield 了, 就返回 undefined
注: 见 demo 中 son4


使用

var son = Father()
son.next()

// Father.prototype === son.__proto__
// true

用法和关系都有点像 var son = new Father()


数据类型

Father 类型是 GeneratorFunction
son 类型是 Generator


方法

Generator.prototype.next()
返回一个由 yield表达式生成的值

Generator.prototype.return()
返回给定的值并结束生成器

Generator.prototype.throw()
向生成器抛出一个错误

Demo

<html>

<head>
	<title>js 生成器 Generator 用法笔记</title>
</head>

<body>

	<script type="text/javascript">
		"use strict"

		function* Father() {
    
    
			yield 'a';
			yield 'b';
			yield 'c';
		}

		var son = Father()
		var son2 = Father()
		var son3 = Father()

		// Generator.prototype.next()

		console.log(son.next())
		console.log(son.next())
		console.log(son.next())

		// Generator.prototype.return()

		console.log(son2.next())
		console.log(son2.return())
		console.log(son2.return("return")) // 提供了参数, 则参数将被设置为返回对象的value属性的值
		console.log(son2.next())

		// Generator.prototype.throw()

		console.log(son3.next())
		try {
    
    
			console.log(son3.throw())
			console.log(son3.throw("throw")) // 提供了参数, 则参数将被设置为返回对象的value属性的值
		} catch (error) {
    
    
			console.warn(error)
			console.warn("用于抛出的异常")
		}
		console.log(son3.next())


		function* Father2() {
    
    
			let a = yield "a";
			console.log('a:', a);
			let b = yield a + 1;
			yield b + 10;
		}
		const son4 = Father2();

		console.log(son4.next())
		console.log(son4.next(100))
		console.log(son4.next())
		console.log(son4.next())

	</script>
</body>

</html>

end


  1. “符合可迭代协议和迭代器协议” 就意味着可以被 for…of 等迭代 ↩︎

猜你喜欢

转载自blog.csdn.net/u013970232/article/details/109513739