---
description: a closure used as an object (also called "module pattern").
---

# closure as object

[JS](../../../..) ⟩ [value](../../..) ⟩ [function](../..) ⟩ [closure](..) ⟩ [example]() ⟩ closure as object

{% hint style="success" %}
a [..](.. "mention") can be used as an [obj](../../../obj "mention"):exclamation:

(this pattern is also called [module-pattern](../../../../module/module-pattern "mention"))
{% 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="👥 相關" %}
* [create](../../../obj/create "mention")
* this pattern is also called [module-pattern](../../../../module/module-pattern "mention").
{% endtab %}

{% tab title="📗 參考" %}
* [ ] [ydkjs-scope-and-closures-v.2](../../../../../master/ref/book/you-dont-know-js-series-v.2/ydkjs-scope-and-closures-v.2 "mention") >&#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 %}
