Factory pattern

Factory pattern

Function User(name, birthday) {
  // only visible from other methods inside User
  function calcAge() {
    return new Date().getFullYear() - birthday.getFullYear();
  }

  return {
    sayHi() {
      alert(`${name}, age:${calcAge()}`);
    }
  };
}

let user = User("John", new Date(2000, 0, 1));
user.sayHi(); // John, age:17

We can create a class without using new at all.

The only benefit of this method is that we can omit new: write let user = User(...) instead of let user = new User(...). In other aspects it's almost the same as the functional pattern.

Related concepts

Factory pattern

Factory pattern — Structure map

Clickable & Draggable!

Factory pattern — Related pages: