_.extend

The method is used to copy the values of all enumerable own and inherited properties from one or more source objects to a target object.

  1. // Underscore
  2. // Lodash: _.assignIn
  3. function Foo() {
  4. this.c = 3;
  5. }
  6. function Bar() {
  7. this.e = 5;
  8. }
  9. Foo.prototype.d = 4;
  10. Bar.prototype.f = 6;
  11. var result = _.extend({}, new Foo, new Bar);
  12. console.log(result);
  13. // output: { 'c': 3, 'd': 4, 'e': 5, 'f': 6 }
  14.  
  15. // Native
  16. function Foo() {
  17. this.c = 3;
  18. }
  19. function Bar() {
  20. this.e = 5;
  21. }
  22. Foo.prototype.d = 4;
  23. Bar.prototype.f = 6;
  24. var result = Object.assign({}, new Foo, Foo.prototype, new Bar, Bar.prototype);
  25. console.log(result);
  26. // output: { 'c': 3, 'd': 4, 'e': 5, 'f': 6 }
  27.  
  28. //Or using a function
  29. const extend = (target, ...sources) => {
  30. let source = [];
  31. sources.forEach(src => {
  32. source = source.concat([src, Object.getPrototypeOf(src)])
  33. })
  34. return Object.assign(target, ...source)
  35. };
  36. console.log(extend({}, new Foo, new Bar));
  37. // output: { 'c': 3, 'd': 4, 'e': 5, 'f': 6 }

Browser Support for Object.assign()

ChromeEdgeFirefoxIEOperaSafari
45.0 ✔34.0 ✔32.0 ✔9.0 ✔