js generator generator usage essay

Generating object is returned by a generator function, and it can meet the protocol and the iterator protocol iteration 1

Example

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

var son = Father()
son.next()

function*

The grammar just has a * sign, there is nothing to explain


yield

The function of yield is a bit like return
calls next() and then executes to yield and returns the content behind it. The
second call to next() continues execution from the place where it returned last time, until the next yield
next() to the end, there is no yield. , Return undefined
Note: See son4 in the demo


use

var son = Father()
son.next()

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

Usage and relationship are a bit like var son = new Father()


type of data

Father type is GeneratorFunction
son type is Generator


method

Generator.prototype.next()
returns a value generated by a yield expression

Generator.prototype.return()
returns the given value and ends the generator

Generator.prototype.throw()
throws an error to the generator

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. "Conforms to the iterable protocol and iterator protocol" means that it can be iterated by for...of ↩︎

Guess you like

Origin blog.csdn.net/u013970232/article/details/109513739