Skip to content

Instantly share code, notes, and snippets.

@rvighne
Last active August 8, 2016 22:50
Show Gist options
  • Save rvighne/dc0d9c3d97e63e811dbe5b6a14ff7603 to your computer and use it in GitHub Desktop.
Save rvighne/dc0d9c3d97e63e811dbe5b6a14ff7603 to your computer and use it in GitHub Desktop.
Polyfill for the Object.assign method using only ES5 (broadly supported) features. Follows the spec exactly (http://www.ecma-international.org/ecma-262/7.0/#sec-object.assign)
// Documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
// Public domain
if (typeof Object.assign !== 'function') {
Object.defineProperty(Object, 'assign', {
configurable: true,
enumerable: false,
writable: true,
// Second argument forces the `length` property to be 2, as per the spec
value: function assign(target, sources) {
if (typeof target === 'undefined')
throw new TypeError("undefined cannot be converted to Object");
else if (target === null)
throw new TypeError("null cannot be converted to Object");
else
target = Object(target);
for (var i = 1; i < arguments.length; ++i) {
var nextSource = Object(arguments[i]);
for (var key in nextSource)
if (nextSource.hasOwnProperty(key))
target[key] = nextSource[key];
}
return target;
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment