Search code examples
javascriptmixins

Nested mixin in JS


I want to create a mixin that creates nested objects on the object that it mixes into.

For example

const mixin = {
  top: {
    middle: {
     bottom: () => {
         console.log(`Hello ${this.name}`);
       }
     }
  }
};

const objectToBeMixed = {
  name: 'Fred Bloggs'
};

Object.assign(objectToBeMixed, mixin);

objectToBeMixed.top.middle.bottom(); // Prints "Hello Fred Blogs"

Does anyone have an idea how to go about this, so that the "this" is bound to the objectToBeMixed?


Solution

  • That's not how you implement mixins. Instead of using a simple object, use a function that accepts context and merges the objects:

    const mixin = context => Object.assign(context, {
      top: {
        middle: {
          bottom: () => {
            console.log(`Hello ${context.name}`);
          }
        }
      }
    });
    
    const objectToBeMixed = {
      name: 'Fred Bloggs'
    };
    
    mixin(objectToBeMixed);
    
    objectToBeMixed.top.middle.bottom(); // Prints "Hello Fred Blogs"