Skip to content

Instantly share code, notes, and snippets.

@neeravp
Last active April 8, 2019 16:31
Show Gist options
  • Save neeravp/11df07737ad1f73612abc5e2b4124d8d to your computer and use it in GitHub Desktop.
Save neeravp/11df07737ad1f73612abc5e2b4124d8d to your computer and use it in GitHub Desktop.
Function to extend existing object by mixing properties and methods from other objects
function omixin(target, ...sources) {
//This function works only when the target is an object
if(typeof target === 'object') {
sources.forEach(source => {
//When merging from another object
if(typeof source === 'object') {
//Add all the instance properties and methods from the source
Object.getOwnPropertyNames(source).forEach(prop => {
let descriptor = Object.getOwnPropertyDescriptor(source, prop);
//To allow overriding the target properties and methods from the source remove the if wrapping
if(target[prop] === undefined) {
Object.defineProperty(target, prop, descriptor);
}
});
//Add all the properties with symbol as keys which are enumerable
Object.getOwnPropertySymbols(source).forEach(symbol => {
let descriptor = Object.getOwnPropertyDescriptor(source, symbol);
if(descriptor.enumerable) {
//To allow overriding the target properties and methods from the source remove the if wrapping
if(target[symbol] === undefined) {
Object.defineProperty(target, symbol, descriptor);
}
}
});
}
});
}
}
@neeravp
Copy link
Author

neeravp commented Apr 8, 2019

This is a slightly modified version of the addMixin function by @calebporzio in his post .

By default, it doesn't allow overriding of methods and property values. However, one can remove the if wrappings as mentioned in the comments in the function to enable overriding.

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