> For the complete documentation index, see [llms.txt](https://lochiwei.gitbook.io/web/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://lochiwei.gitbook.io/web/js/val/func/closure/examples/closure-as-object.md).

# closure as object

[JS](/web/js.md) ⟩ [value](/web/js/val.md) ⟩ [function](/web/js/val/func.md) ⟩ [closure](/web/js/val/func/closure.md) ⟩ [example](/web/js/val/func/closure/examples.md) ⟩ closure as object

{% hint style="success" %}
a [closure](/web/js/val/func/closure.md) can be used as an [object](/web/js/val/obj.md):exclamation:

(this pattern is also called [module pattern](/web/js/module/module-pattern.md))
{% endhint %}

{% tabs %}
{% tab title="💾 程式" %}

* replit：[closure as object](https://replit.com/@pegasusroe/closure-as-object#index.js)

```javascript
// returns an object with closed over properties.
function Person(name, age) {

    // 🔸 private properties
    //    • `name`, `age` are treated as private properties.

    // ⭐️ the object to be returned (with exposed methods)
    const obj = { sayHi };

    // -------- define getter/setter/method --------

    // 🔸 obj.name (getter/setter)
    Object.defineProperty(obj, 'name', {
        get() { return name },
        set(value) { name = value },
    });

    // 🔸 obj.sayHi (exposed method)
    function sayHi() {
        console.log(`Hi, my name is ${name}, I'm ${age} years old.`);
    }
    
    return obj;
}

// instances
const joe = Person('Joe', 10);
const jane = Person('Jane', 8);

joe.name = 'Superman';    // "setter" called

joe.sayHi();    // Hi, my name is Superman, I'm 10 years old.
jane.sayHi();   // Hi, my name is Jane, I'm 8 years old.
```

{% endtab %}

{% tab title="👥 相關" %}

* [creating objects](/web/js/val/obj/create.md)
* this pattern is also called [module pattern](/web/js/module/module-pattern.md).
  {% endtab %}

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

* [ ] [YDKJS: Scope & Closures (v.2)](/web/master/ref/book/you-dont-know-js-series-v.2/ydkjs-scope-and-closures-v.2.md) >&#x20;
  * [ ] Ch.7 > [Per Variable or Per Scope?](https://github.com/getify/You-Dont-Know-JS/blob/2nd-ed/scope-closures/ch7.md#per-variable-or-per-scope)
  * [ ] Ch. 8 > [Modules](https://github.com/getify/You-Dont-Know-JS/blob/2nd-ed/scope-closures/ch8.md#modules-stateful-access-control)
    {% endtab %}
    {% endtabs %}
