The absorb() method

After reviewing the comments from everyone on the previous post, I’ve come up with the next generation of the absorb() function: the absorb() method. It occurred to me that this function really was begging to be a method of Object. So, without further adieu:

Object.absorb = function (destination /*:Object*/, source /*:Object*/, overwrite /*:Boolean*/) /*:Object*/ {
    for (var key in source) {
        if (overwrite || typeof destination[key] == "undefined"){
            destination[key] = source[key];
        }
    }

    return destination;
}

Object.prototype.absorb = function (source /*:Object*/, overwrite /*:Boolean*/) /*:Object*/ {
    return Object.absorb(this, source, overwrite);
}

Yes, there are two versions. The first is a generic that I’ve placed as a method of Object in order to avoid polluting the global scope. This can be used just like the absorb() function I originally wrote about, such as:

Object.absorb(Array.prototype, {
    forEach: function () { ... }
});

The second method is inherited by other others (of course, not DOM objects in Internet Explorer), but it allows easier access to the method:

Array.prototype.absorb({
    forEach: function () { ... }
});

Also, thanks to the comment from Les, each method now returns the destination object, so calls can be chained together like this:

Array.prototype.absorb({
    forEach: function () { ... }
}).absorb({
map : function () { ... }
})

Of course, if you want to ignore the native or already existing methods, just pass in true as the second argument; this causes absorb() to overwrite any existing methods of the same name:

Array.prototype.absorb({
    forEach: function () { ... }
}, true);

And that’s about it. Thanks to everyone who contributed comments on the last post. I feel like this function has evolved into a much more useful and usable form.

Was this helpful? If you found this post helpful, I would very much appreciate your support. Donations of any amount gratefully accepted.