assign.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. var arrayEach = require('./arrayEach')
  2. var keys = require('./keys')
  3. var isArray = require('./isArray')
  4. var clone = require('./clone')
  5. var objectAssignFns = Object.assign
  6. function handleAssign (destination, args, isClone) {
  7. var len = args.length
  8. for (var source, index = 1; index < len; index++) {
  9. source = args[index]
  10. arrayEach(keys(args[index]), isClone ? function (key) {
  11. destination[key] = clone(source[key], isClone)
  12. } : function (key) {
  13. destination[key] = source[key]
  14. })
  15. }
  16. return destination
  17. }
  18. /**
  19. * 将一个或多个源对象复制到目标对象中
  20. *
  21. * @param {Object} target 目标对象
  22. * @param {...Object}
  23. * @return {Boolean}
  24. */
  25. var assign = function (target) {
  26. if (target) {
  27. var args = arguments
  28. if (target === true) {
  29. if (args.length > 1) {
  30. target = isArray(target[1]) ? [] : {}
  31. return handleAssign(target, args, true)
  32. }
  33. } else {
  34. return objectAssignFns ? objectAssignFns.apply(Object, args) : handleAssign(target, args)
  35. }
  36. }
  37. return target
  38. }
  39. module.exports = assign