javascript mix-in pattern

Mix any number of objects and mix them all into a new object:

 
function mix() {
    var arg, prop, child = {};
    for (arg = 0; arg < arguments.length; arg += 1) {
        for (prop in arguments[arg]) {
            if (arguments[arg].hasOwnProperty(prop)) {
                child[prop] = arguments[arg][prop];
            }
        }
    }
    return child;
}
 
var cake = mix(
    {
        eggs: 2,
        large: true
    }, {
        butter: 1,
        salted: true
    }, {
        flour: "3 cups"
    }, {
        sugar: "sure!"
    }
);
 
console.dir(cake);

Return:

Object:
butter: 1
eggs: 2
flour: "3 cups"
large: true
salted: true
sugar: "sure!"

Leave a Reply

Your email address will not be published. Required fields are marked *