为什么课程里for in可以遍历实例原型里的属性,我自己写的demo不可以
来源:7-3 -3 扩展接口 - 混合对象实现+ demo 编写

桃花开了
2020-02-20
class Axios {
request() {
console.log('a')
}
get() {
console.log('b')
}
delete() {
console.log('c')
}
}
const context = new Axios();
for (let key in context) {
console.log(key)
}
这里打印不出key的值。
然而在课程里extend却能遍历出key值来,这是为什么呢
function createInstance(): AxiosInstance {
const context = new Axios()
const instance = Axios.prototype.request.bind(context)
extend(instance, context)
return instance as AxiosInstance
}
export function extend <T, U>(to: T, from: U): T & U{
for (const key in from) {
console.log(key);
(to as T & U)[key] = from[key] as any
}
return to as T & U;
}
extend转为js后是
function extend(to, from) {
for (var key in from) {
to[key] = from[key];
}
return to;
}
extend函数转化后的函数也是在遍历Axios的实例啊
写回答
1回答
-
因为 Axios Class 被编译生成 Function 后就可以遍历了。
012020-02-21
相似问题