重写call

三个功能:获取fn参数、改变this(重难点)、获取返回值
改变this指向技巧:使用t.fn,将要执行的fn作为t对象的属性,如此一来 fn中的this将指向t

  1. //手写call源码
  2. Function.prototype.myCall = function(){
  3. const args = Array.from(arguments)
  4. //改变this的值
  5. const t = args.shift()
  6. const self = this//保存this指向到self变量中,此处的this为调用者fn
  7. t.fn = self //此处可理解创建self变量的意义,为了指向同一块地址
  8. //获取fn参数 并传入fn执行
  9. const res = t.fn(...args)//将第二位开始后的参数作为fn参数传入并执行
  10. delete t.fn //t.fn只是为了便于改变this指向的技巧,在执行完fn后应该删除掉其捆绑关系
  11. //获取返回值
  12. //只需声明res接收fn调用后的返回值即可return返回值
  13. return res
  14. }
  15. //fn函数
  16. function fn(a,b){
  17. console.log('a',a)
  18. console.log('b',b)
  19. console.log('this',this)
  20. return 'hello'
  21. }
  22. //调用myCall
  23. const res = fn.myCall({npc:18},20,30)
  24. console.log('res',res)

重写apply

重写bind

重写new

重写typeof

重写instanceof