Prototype-based pattern

Prototype-based pattern

Function User(name, birthday) {
  this._name = name;
  this._birthday = birthday;
}

User.prototype._calcAge = function() {
  return new Date().getFullYear() - this._birthday.getFullYear();
};

User.prototype.sayHi = function() {
  alert(`${this._name}, age:${this._calcAge()}`);
};

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

In this pattern, all methods are in User.prototype that is shared between all user objects. An object itself only stores the data.

Pattern is more memory-efficient.

Related concepts

Prototype-based pattern — Structure map

Clickable & Draggable!

Prototype-based pattern — Related pages: