Skip to content

Instantly share code, notes, and snippets.

@neeravp
Last active April 8, 2019 16:23
Show Gist options
  • Save neeravp/c23fcd3ebd239c8d3a555c1a1d03495d to your computer and use it in GitHub Desktop.
Save neeravp/c23fcd3ebd239c8d3a555c1a1d03495d to your computer and use it in GitHub Desktop.
Function to mixin properties including getters and setters from one javascript object to another.
function mixin(target, ...sources) {
sources.forEach(source => {
let descriptors = Object.keys(source).reduce((descriptors, key) => {
descriptors[key] = Object.getOwnPropertyDescriptor(source, key);
return descriptors;
}, {});
Object.getOwnPropertySymbols(source).forEach(sym => {
let descriptor = Object.getOwnPropertyDescriptor(source, sym);
if(descriptor.enumerable) {
descriptors[sym] = descriptor;
}
});
Object.defineProperties(target, descriptors);
});
return target;
}
@neeravp
Copy link
Author

neeravp commented Apr 7, 2019

All credit to @calebporzio for the mixin function. He has explained it in his blog .

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment