前端手写(十七)——手写Object.assign

x33g5p2x  于2022-03-31 转载在 其他  
字(0.6k)|赞(0)|评价(0)|浏览(333)

一、写在前面
Object.assign其实也就是浅拷贝,传入的参数可以为任意多个。并且后面的全部属性拷贝到前面的对象上。
二、手写实现

  1. Object.defineProperty(Object, 'assign', {
  2. value: function (target, ...args) {
  3. if (target == null) {
  4. return new TypeError('Cannot convert undefined or null to object');
  5. }
  6. // 目标对象需要统一是引用数据类型,若不是会自动转换
  7. const to = Object(target);
  8. for (let i = 0; i < args.length; i++) {
  9. // 每一个源对象
  10. const nextSource = args[i];
  11. if (nextSource !== null) {
  12. // 使用for...in和hasOwnProperty双重判断,确保只拿到本身的属性、方法(不包含继承的)
  13. for (const nextKey in nextSource) {
  14. if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
  15. to[nextKey] = nextSource[nextKey];
  16. }
  17. }
  18. }
  19. }
  20. return to;
  21. },
  22. // 不可枚举
  23. enumerable: false,
  24. writable: true,
  25. configurable: true,
  26. })

相关文章