closure as object

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

JSvaluefunctionclosureexample ⟩ closure as object

a closure can be used as an object

(this pattern is also called module pattern)

// 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.

Last updated