ref – https://blog.bitsrc.io/understanding-mixins-in-javascript-de5d3e02b466
Mixin is a way properties are added to objects without using inheritance — Darren Jones
Mixins are a form of object composition, where component features get mixed into a composite object so that properties of each mixin become properties of the composite object. — Eric Elliot
Let’s create a destination object to contain all the data.
Then we create a whole bunch of other objects with properties.
Finally, we’ll write our custom assign to “mixin” these objects with properties into our destination object like so:
1 2 3 4 5 6 7 8 |
const mydetails = {} const firstname = { firstname: "ricky" } const surname = { surname: "qi ji" } const occupation = { occupation: "Software Developer" } console.log(mydetails) // {} myAssign(mydetails,surname, firstname, occupation); console.log(mydetails) |
The result of mydetails would be:
{surname: “qi ji”, firstname: “ricky”, occupation: “Software Developer”}
surname: “qi ji”
firstname: “ricky”
occupation: “Software Developer”
__proto__: Object
It mixed in all the properties of the other objects.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
// ...src takes in unknown number of parameters, and convert it to array function myAssign(dest, ...src) { // typeof dest is Object // dest instanceof Array would return true if(typeof dest == 'object') { for(let s of src) { // loop through every element in this array if(typeof s == 'object') { // if the item is an object // for each key in this item, i.e firstname, surname....etc for(prp of Object.keys(s)) { console.log(`key ${prp}`); console.log(`append or access key ${prp} in dest obj, have reference point to source object`); dest[prp] = s[prp] } } } } } const mydetails = {} const firstname = { firstname: "ricky" } const surname = { surname: "qi ji" } const occupation = { occupation: "Software Developer" } // pass in our destination, and source objects. myAssign(mydetails,surname, firstname, occupation); console.log(mydetails) |