JS Built-ins
DesignPatternsintermediate

Factory β€” Objects with methods

πŸ“– Usage Example
function createCounter(start = 0) {
  let count = start;
  return {
    increment() { count++; },
    value() { return count; },
  };
}
const c = createCounter(10);

Factory functions can capture private state via closures.

Factory Pattern β€” Creating Objects with Methods

Factory-created objects can have methods, not just properties.

Challenge: Implement a createButton(label) factory that returns an object with:

  • label property
  • click() method that returns 'button clicked'
  • getText() method that returns the label

Example:

const btn = createButton('Submit')
btn.label // 'Submit'
btn.click() // 'button clicked'
btn.getText() // 'Submit'
πŸ’‘ Hints (3)
  • β€’ Return object with methods
  • β€’ Use this to access the label in methods
  • β€’ Each factory call creates a new object with its own label