Objects as Namespaces

2021-10-05

Attaching properties into objects are a nice way to create namespaces in JavaScript.

let Accounts = {
  create({ name, email, password }) {
    /* .. */
  }
}

Accounts.create({
  name: 'Gustavo',
  email: 'gustavo@email.com',
  password: '***'
})

If somehow Accounts needs a dependency, you can transform it into a factory function and inject the dependency:

let createAccounts = (repo) => ({
  create({ name, email, password }) {
    /* .. */
  }
})

const accounts = createAccounts(createRepo())
// {create: ƒ}
#design pattern#typescript#javascript

📝 Edit this page