โœจclosure as object

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

JS โŸฉ value โŸฉ function โŸฉ closure โŸฉ example โŸฉ 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