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回答
-
也可以呀
012024-06-18