assign.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. var assignValue = require('./_assignValue'),
  2. copyObject = require('./_copyObject'),
  3. createAssigner = require('./_createAssigner'),
  4. isArrayLike = require('./isArrayLike'),
  5. isPrototype = require('./_isPrototype'),
  6. keys = require('./keys');
  7. /** Used for built-in method references. */
  8. var objectProto = Object.prototype;
  9. /** Used to check objects for own properties. */
  10. var hasOwnProperty = objectProto.hasOwnProperty;
  11. /** Built-in value references. */
  12. var propertyIsEnumerable = objectProto.propertyIsEnumerable;
  13. /** Detect if properties shadowing those on `Object.prototype` are non-enumerable. */
  14. var nonEnumShadows = !propertyIsEnumerable.call({ 'valueOf': 1 }, 'valueOf');
  15. /**
  16. * Assigns own enumerable string keyed properties of source objects to the
  17. * destination object. Source objects are applied from left to right.
  18. * Subsequent sources overwrite property assignments of previous sources.
  19. *
  20. * **Note:** This method mutates `object` and is loosely based on
  21. * [`Object.assign`](https://mdn.io/Object/assign).
  22. *
  23. * @static
  24. * @memberOf _
  25. * @since 0.10.0
  26. * @category Object
  27. * @param {Object} object The destination object.
  28. * @param {...Object} [sources] The source objects.
  29. * @returns {Object} Returns `object`.
  30. * @see _.assignIn
  31. * @example
  32. *
  33. * function Foo() {
  34. * this.c = 3;
  35. * }
  36. *
  37. * function Bar() {
  38. * this.e = 5;
  39. * }
  40. *
  41. * Foo.prototype.d = 4;
  42. * Bar.prototype.f = 6;
  43. *
  44. * _.assign({ 'a': 1 }, new Foo, new Bar);
  45. * // => { 'a': 1, 'c': 3, 'e': 5 }
  46. */
  47. var assign = createAssigner(function(object, source) {
  48. if (nonEnumShadows || isPrototype(source) || isArrayLike(source)) {
  49. copyObject(source, keys(source), object);
  50. return;
  51. }
  52. for (var key in source) {
  53. if (hasOwnProperty.call(source, key)) {
  54. assignValue(object, key, source[key]);
  55. }
  56. }
  57. });
  58. module.exports = assign;