JavaScript question detail
What are the different kinds of generators
There are five kinds of generators,
- Generator function declaration:
function* myGenFunc() {
yield 1;
yield 2;
yield 3;
}
const genObj = myGenFunc();
- Generator function expressions:
const myGenFunc = function* () {
yield 1;
yield 2;
yield 3;
};
const genObj = myGenFunc();
- Generator method definitions in object literals:
const myObj = {
*myGeneratorMethod() {
yield 1;
yield 2;
yield 3;
},
};
const genObj = myObj.myGeneratorMethod();
- Generator method definitions in class:
class MyClass {
*myGeneratorMethod() {
yield 1;
yield 2;
yield 3;
}
}
const myObject = new MyClass();
const genObj = myObject.myGeneratorMethod();
- Generator as a computed property:
const SomeObj = {
*[Symbol.iterator]() {
yield 1;
yield 2;
yield 3;
},
};
console.log(Array.from(SomeObj)); // [ 1, 2, 3 ]