# generator function as ...

[JS](https://lochiwei.gitbook.io/web/js) ⟩ [objects](https://lochiwei.gitbook.io/web/js/val/obj) ⟩ [built-in](https://lochiwei.gitbook.io/web/js/val/builtin) ⟩ [Generator](https://lochiwei.gitbook.io/web/js/iteration/generator) ⟩ [generator function](https://lochiwei.gitbook.io/web/js/iteration/generator/func) ⟩ as ...

{% hint style="success" %}
[](https://lochiwei.gitbook.io/web/js/iteration/generator/func "mention") can be used as：

* [variable](https://lochiwei.gitbook.io/web/js/variable "mention"), [method](https://lochiwei.gitbook.io/web/js/val/obj/method "mention")
  {% endhint %}

{% tabs %}
{% tab title="💈範例" %}

* replit：[generator functions as ...](https://replit.com/@pegasusroe/generator-function-as-method#index.js)

```javascript
// ⭐️ function* expressions

//           ╭─────── 🔸 1. as "variable" ───────╮
   const f = function*() { yield 'a'; yield 'b'; };
// ╰────────────── const statement ───────────────╯

let obj = {

    // (part of) keys
    x: 1, y: 2, z: 3,

    //╭─────────────── 🔸 2. as "method" ───────────────╮
    *keys() {
        for (let key of Object.keys(this)) { yield key }
    }
};

// 1. as variable
[...f()]            // [ 'a', 'b' ]

// 2. as method
[...obj.keys()]     // [ 'x', 'y', 'z', 'keys' ]
```

{% endtab %}

{% tab title="📗 參考" %}

* [ ] JavaScript: The Definitive Guide ⟩ 12.3 Generators
  {% endtab %}
  {% endtabs %}
