Advanced Object Patterns and Mixins

Difficulty: Intermediate

Question

Explain Object.create(), and mixin patterns in JavaScript.

Answer

Object.create(proto) creates a new object with the specified prototype, enabling prototypal inheritance without constructors.

Mixins extend objects with behavior from multiple sources - a way to compose functionality without deep inheritance chains.

Object.assign(target, ...sources) shallow-copies enumerable own properties from sources into target.

OLOO (Objects Linked to Other Objects) by Kyle Simpson prefers prototypal delegation over class-based inheritance.

Code examples

Object.create and Prototypal Inheritance

const animal = {
  breathe() { return `${this.name} breathes`; },
  describe() { return `I am ${this.name}`; }
};

const dog = Object.create(animal);
dog.bark = function() { return `${this.name} barks`; };

const myDog = Object.create(dog);
myDog.name = 'Rex';

console.log(myDog.breathe());
console.log(myDog.bark());

console.log(Object.getPrototypeOf(myDog) === dog);
console.log(Object.getPrototypeOf(dog) === animal);

const pureMap = Object.create(null);
pureMap.key = 'value';
console.log(pureMap.hasOwnProperty);

Object.create() sets up the prototype chain explicitly. Object.create(null) creates a pure dictionary with no inherited methods.

Mixin Factory Pattern

const Serializable = (Base) => class extends Base {
  serialize() { return JSON.stringify(this); }
};

const Timestamped = (Base) => class extends Base {
  constructor(...args) {
    super(...args);
    this.createdAt = Date.now();
  }
};

const Validatable = (Base) => class extends Base {
  validate() {
    return Object.keys(this).every(key =>
      this[key] !== null && this[key] !== undefined
    );
  }
};

class User extends Validatable(Timestamped(Serializable(class {}))) {
  constructor(name, email) {
    super();
    this.name = name;
    this.email = email;
  }
}

const user = new User('Alice', 'alice@example.com');
console.log(user.validate());
console.log(typeof user.serialize());
console.log(user.createdAt > 0);

Mixin factories take a Base class and return an extended class. Composing multiple mixins adds behaviors without deep inheritance.

Key points

Concepts covered

Object.create, Mixins, Object composition, Prototypal Inheritance