bind 问题

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

诺巴蒂

2021-11-30

class Axios {
  request() {}

  get(){ this.console()}

  console() {
    console.log(111)
  }
}
/*  */
const context = new Axios()
const instance = Axios.prototype.request.bind(context)
instance.get = context.get

instance.get()

这个没太理解,bind 解决的不是 request 的 this 指向问题吗,get 的指向问题是怎么解决的,我执行这个 demo 是报错的

写回答

1回答

ustbhuangyi

2021-12-01

class Axios {

request() {}


get(){ this.console()}


console() {

console.log(111)

}

}


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

}

/*  */

const context = new Axios()

const instance = Axios.prototype.request.bind(context)

extend(instance, context)

// instance.get = context.get


console.log(instance.get())



这么写是可以的,但要保证 TSConfig 的编译 target 是 es5,这样 class 部分就会编译了。

0
1
诺巴蒂
懂了,因为 extend 把context所有方法都复制了一遍到 instance 里,所以 this 取的还是 instance 不是 context,bind 是因为 request 的执行可能不是通过调用的方式
2021-12-06
共1条回复

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

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

2629 学习 · 877 问题

查看课程