extend实现

来源:7-3 -3 扩展接口 - 混合对象实现+ demo 编写

许愿瓶啊

2020-08-17

// export function extend<T, U>(to: T, from: U): T & U {
//
//   for (const key in from) {
//     (to as T & U)[key] = from[key] as any
//   }
//
//   return to as T & U
// }

export function extend<T, U>(to: T, from: U): T & U {
  function copy(instance: Record<string, any>) {
    Object.getOwnPropertyNames(instance).forEach((key) => {
      Object.assign(to, {
        [key]: instance[key]
      })
    })

    const proto = Reflect.getPrototypeOf(instance)

    if (proto !== null) {
      copy(proto)
    }
  }

  copy(from)

  return to as T & U
}

es6规定原型上的方法是不可枚举的,这里之所以可以实现是ts编译器的编译目标是es5有关吧?尝试了下es6实现的extend方法,使用es6实现extend会不会更好点,这样即使编译目标是es6这段代码也是可以正常运行的。

写回答

1回答

ustbhuangyi

2020-08-18

也可以呀

0
1
MirorXu
老师,我的extend方法也有问题,最终的axios函数对象没有get、post方法, for in 无法遍历context(即 Axios实例)的原型方法,因为不可枚举。 extend的实现感觉不是很好呢
2024-06-18
共1条回复

下一代前端开发语言 TypeScript从零重构axios

课程从零开始重构功能完整的JS库,是学习造轮子的不二之选!

2629 学习 · 877 问题

查看课程