Last active
April 8, 2019 16:31
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} | |
}); | |
} | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.