Skip to content

21. 实现 Object.assign

js
Object.assign2 = function(target, ...sources) {
  if (target == null) {
    throw new TypeError('Cannot convert undefined or null to object');
  }

  let to = Object(target);
  for (let i = 0; i < sources.length; i++) {
    let from = sources[i];
    if (from != null) {
      for (let key in from) {
        if (Object.prototype.hasOwnProperty.call(from, key)) {
          to[key] = from[key];
        }
      }
    }
  }

  return to;
};