Skip to content

Instantly share code, notes, and snippets.

@spiralx
Created July 6, 2015 17:31
Show Gist options
  • Save spiralx/68cf40d7010d829340cb to your computer and use it in GitHub Desktop.
Save spiralx/68cf40d7010d829340cb to your computer and use it in GitHub Desktop.
Object.assign() browser polyfill
if (!Object.assign) {
Object.defineProperty(Object, 'assign', {
enumerable: false,
configurable: true,
writable: true,
value: function(target) {
'use strict';
if (target === undefined || target === null) {
throw new TypeError('Cannot convert first argument to object');
}
var to = Object(target);
for (var i = 1; i < arguments.length; i++) {
var nextSource = arguments[i];
if (nextSource === undefined || nextSource === null) {
continue;
}
nextSource = Object(nextSource);
var keysArray = Object.keys(Object(nextSource));
for (var nextIndex = 0, len = keysArray.length; nextIndex < len; nextIndex++) {
var nextKey = keysArray[nextIndex];
var desc = Object.getOwnPropertyDescriptor(nextSource, nextKey);
if (desc !== undefined && desc.enumerable) {
to[nextKey] = nextSource[nextKey];
}
}
}
return to;
}
});
}
@ianmin2
Copy link

ianmin2 commented Jul 21, 2018

Thanks a million
Just Saved My Life of a whole load of stress.

@athlan20
Copy link

thx

@J2thatsme
Copy link

thx

@cpcallen
Copy link

cpcallen commented Feb 2, 2022

This sets the wrong values for Object.assign.name (it will get set to value instead of assign) and Object.assign.length (it will get set to 1 instead of 2).

I recommend the following approach instead, which has the additional advantage being more readable:

if (!Object.assign) {
  Object.assign = function assign(target, source) {
    /* implementation omitted */
  };
  Object.defineProperty(Object, 'assign', {enumerable: false});
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment