Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading