Skip to content

Instantly share code, notes, and snippets.

@Naoray
Created March 25, 2019 09:09
Show Gist options
  • Save Naoray/f105df00df93f6f95f76a3ce4ba8607f to your computer and use it in GitHub Desktop.
Save Naoray/f105df00df93f6f95f76a3ce4ba8607f to your computer and use it in GitHub Desktop.
Using the equivalent of php trait
// taken from http://calebporzio.com/equivalent-of-php-class-traits-in-javascript/
function addMixin(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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment