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

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

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

Object.defineProperty(Object, 'assign', {
  value: function (target, ...args) {
    if (target == null) {
      return new TypeError('Cannot convert undefined or null to object');
    }

    // 目标对象需要统一是引用数据类型,若不是会自动转换
    const to = Object(target);

    for (let i = 0; i < args.length; i++) {
      // 每一个源对象
      const nextSource = args[i];
      if (nextSource !== null) {
        // 使用for...in和hasOwnProperty双重判断,确保只拿到本身的属性、方法(不包含继承的)
        for (const nextKey in nextSource) {
          if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
            to[nextKey] = nextSource[nextKey];
          }
        }
      }
    }
    return to;
  },
  // 不可枚举
  enumerable: false,
  writable: true,
  configurable: true,
})

相关文章

微信公众号

最新文章

更多