# closure as object

[JS](https://lochiwei.gitbook.io/web/js) ⟩ [value](https://lochiwei.gitbook.io/web/js/val) ⟩ [function](https://lochiwei.gitbook.io/web/js/val/func) ⟩ [closure](https://lochiwei.gitbook.io/web/js/val/func/closure) ⟩ [example](https://lochiwei.gitbook.io/web/js/val/func/closure/examples) ⟩ closure as object

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

(this pattern is also called [module-pattern](https://lochiwei.gitbook.io/web/js/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](https://lochiwei.gitbook.io/web/js/val/obj/create "mention")
* this pattern is also called [module-pattern](https://lochiwei.gitbook.io/web/js/module/module-pattern "mention").
  {% endtab %}

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

* [ ] [ydkjs-scope-and-closures-v.2](https://lochiwei.gitbook.io/web/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 %}
